MySQL, MySQLi, PDO or something else - how best to talk to databases from PHP
Archive - Originally posted on "The Horse's Mouth" - 2011-09-24 14:05:35 - Graham EllisOne of the consideration that users of Open Source programming languages have make is which one of many ways to do any particular task. Open Source tends to result in lots of very clever facilities being provided, many of which overlap in their use, and many modules being provided via libraries such as Pear and Pecl [PHP names being used]. A good example of this is database access - even when you've selected you main database engine you may be left with a baffling array of different ways to access it. I've just completed a short demonstration piece that shows our different pieces of code for accessing the same MySQL database.
I have four different ways I can talk to MySQL ...
a) MySQL_xxx routines. The "original". Quick and easy to code. For a single database connection, there's no need to pass around a "which connection" variable. Gets a bit messy when you may want to make several connections, as you have to then switch to using a connection variable (so you may need to refactor) and horribly tied to MySQL.
b) MySQLi_xxx routines, using a functional (structured) approach. Very similar in many ways to the mysql_ routines, but you have to pass around a "which connection" variable. So this avoids you walking into a cul-de-sac in your early coding, as you can easily add another connection later. Still horribly tied to MySQL.
c) MySQLi_xxx routines, using an OO approach. If you're writing in an object oriented mode, these are far nicer to use - you set up connection objects, get back query objects, and the whole thing naturally follows the OO paradigm. There's no way you can even be tempted along a single connection approach. Oh - but still tied to MySQL ... to a slightly lesser extent.
d) Using PDO. The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. So PDO lets you state once that it's MySQL you're using and then go ahead with your code without having to keep saying mysql-this and mysql-that. You do still need to be careful not to be tempted into using facilities which are MySQL only, but with care you can write more portable code.
The source code of the demonstration is [here] and you can see the sort of results it would produce when run [here].
We have a brief section on how you may use PHP to talk to the MySQL database on our MySQL course, and we cover talking to various SQL databases including SQLite and MySQL on our PHP Courses.