Everything is happy when you are running around with functions like mysql_query() and mysql_fetch_array() – but what if you ever have to change from MySQL to another database software? You could just do a str_replace() on the contents of your scripts, but that’s not the point. There’s an easier way.

A database handler class is a class that handles all requests to the database. A really simple one would look like this:
class DatabaseHandler {
function connect( $host, $username, $password, $database ) {
mysql_connect( $host, $username, $password );
mysql_select_db( $database );
}
function query( $query ) {
return mysql_query( $query );
}
}
We could use this and call DatabaseHandler::connect() to connect and DatabaseHandler::query() to call a query. It seems pretty stupid, but it can be very helpful. Here’s 5 reasons how it can make your life easier:
-
Easily change database software
When using a database handler class, it’s a lot easier to switch the way that you run a query. This could be as simple as changing
mysql_query()topg_query()or as complicated as rewriting the process by which your database handler creates a query. -
Make complicated queries simple
Although knowledge of the query language is required to create the database handler class, you could write a class (or find a class) that is powerful enough to cover all query creation for you. In times before I started using frameworks for large projects, I had a database class that only required me to pass an array into one of its methods. It took the array, created a query string, and then queried the database.
-
Keep track of statistics
Imagine trying to track all of the times that
mysql_query()was called. That would be a hassle. When using a database handler, it’s pretty easy to add a line in your query method to count the number of queries used to generate the page. It’s also pretty easy to time those queries and see how much time your script spent getting data from the database. -
Debug with more power
It can be help to have a list of queries that were sent to the database during script execution. I used to edit my database handler so that it would save a list of queries and then output them at the end every page.
-
One step closer to a full framework
Using a database class is one step using to using a full framework. After you start using a database class, you can use similar logic for other aspects of your application, such as templates. Eventually, you will be ready for a full framework that will save time developing.
These are just five ways that using a database handler will help you – if you have any more, please leave a comment! :)
As for finding a database handler – you could always create your own. If you aren’t up for that, here’s one that you could check out: MySQLi.
Thanks for reading! Again, if you have any ideas (or opinions), please leave a comment! I look forward to hearing your thoughts.