Simple Database Connection Class With PDO


PHP Database Connection Class Using PDO(PHP Data Objects)

The purpose of this two small code snippets is to provide a very lean, simple database connection class that you can use to query your mySQL database using PDO(PHP Data Objects). The coding consists of a pair of files; one of which is the class and the other which is the file which instantiates an object that provides a useful $db variable which can be used to make the queries.

Overview

A new object is instantiated and the database parameters are passed into the constructor. After the parameters are passed in, the db_connect() method is called and it returns the $db. The class does the work of creating a new instance of the PDO object and then returns it with the name $db. Now, $db can be used to do select, insert, update and delete statements. Since you are using a PDO object, you stick with the various methods that are available with the class; such as the execute() method. 

Class File

class DatabaseConnect
{
    private $host;
    private $user;
    private $pw;
    private $database;


    function __construct($host, $user, $pw, $database)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->database = $database;
    }


    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }

}


Other File

include("class-login-PDO.php");

$host = "localhost";
$user = "username";
$pw = "password";
$database = "database_name";

$login = new DatabaseConnect($host, $user, $pw, $database);

$db = $login->db_connect();

var_dump($db);

$command = $db->prepare("SELECT * FROM cms");
$command->execute();
$result = $command->fetchAll();

foreach ($result as $row) {
    $my_array[] = $row;
}

print_r($my_array);