Thursday 19 July 2012

Simple PDO Class

For some reason, maybe it was my first (negative) introduction to OOP through C++, I've always hated those (::) double colons. So, when I started to look at PHP Data Objects (PDO), although it seemed like  a good idea, I couldn't get over the fact that I was opening myself up to using static class and methods with all the syntax which goes with it.

So I started to create a simple database class which made use of PDO, which would be a little friendlier to call. Humble beginnings these. First I created an ini file for all the settings, which looks something like this:

DB_TYPE = mysql
DB_HOST = localhost
DB_USERNAME = jimmy
DB_PASSWORD = password
DB_NAME = testdb

Then, I created the database class which called the ini file thus:

<?php
class database
{
private $config;
private $connection;
private $pdoString;
  function __construct()
{
$this->config = (object) parse_ini_file('config.ini', true);
$this->pdoString = $this->config->DB_TYPE;
$this->pdoString .= ':dbname='.$this->config->DB_NAME;
$this->pdoString .= ';host='.$this->config->DB_HOST;
$this->connection = new PDO($this->pdoString, $this->config->DB_USERNAME, $this->config->DB_PASSWORD);
}


public function query($q)
{
    return $this->connection->query($q);
}


function __destruct()
{
$this->connection = NULL;
}
}
?>
Finally, I created a calling page to see how it ran:

<?php
require_once 'database.class.php';
$db = new database;
$arr = $db->query('SELECT * FROM users');
foreach($arr as $row)
{
echo $row['username'].'<br />';
}
?>
It's a start.


No comments:

Post a Comment