Database classes & best practices

Hi, I was just wondering if somebody could help me out or point me in the direction of the answer.

I have just started working with objects in PHP and have noticed that database querys in PHP don’t work the same way as in procedural PHP.

The database classes I have come across tend to use seperate methods for specifying the query and then running it. For example

$query = $this->database->query('QUERY HERE');

Also the results are usually returned as an object instead of a result variable like i’m used to in procedural PHP.

I’m sure database classes vary depending on who writes them but this seems to be a common way of doing it. I was just wondering what the theory behind this is, why it is done like this and how I can write my own database class using a similar method.

Are there any books or online resources you can recommend to help me get my head around this?


Separating building the query from executing it allows you to add functionality to the query object.

$query = $this->database->query('SELECT * FROM table WHERE field = :value');
$query->setParameter('value','some value');


Read and understand the PDO section of the PHP manual. Consider PDO to be a reference implementation.

And then if you really want your head to explode, read the Doctrine 2 ORM manual:

13. Doctrine Query Language — Doctrine 2 ORM v2.1 documentation

How people structure their database class is usually a question of personal taste.

If you look at the de-facto PHP database class ([fphp]PDO[/fphp]), you can actually choose how you want to get your results back. That link is also a very good place to get started with reading more about database objects.

Thanks for the replies, I will start getting to grips with PDO.