PHP Database Access: Are You Doing It Correctly?

We've covered PHP's PDO API a couple of times here on Nettuts+, but, generally, those articles focused more on the theory, and less on the application. This article will fix that!

To put it plainly, if you're still using PHP's old mysql API to connect to your databases, read on!

Looking for a Shortcut?

If you're working with PHP or MySQL and need a quick fix for an error in your code, you can have any single error fixed quickly and affordably by PHP developer Araneux on Envato Studio.

PHP developer Araneux on Envato Studio.

What?

It's possible that, at this point, the only thought in your mind is, "What the heck is PDO?" Well, it's one of PHP's three available APIs for connecting to a MySQL database. "Three," you say? Yes; many folks don't know it, but there are three different APIs for connecting:

  • mysql
  • mysqli - MySQL Improved
  • pdo - PHP Data Objects

The traditional mysql API certainly gets the job done, and has become so popular largely due to the fact that it makes the process of retrieving some records from a database as easy as possible. For example:

Yes, the code above is fairly simple, but it does come with its significant share of downsides.

  • Deprecated: Though it hasn't been officially deprecated - due to widespread use - in terms of best practice and education, it might as well be.
  • Escaping: The process of escaping user input is left to the developer - many of which don't understand or know how to sanitize the data.
  • Flexibility: The API isn't flexible; the code above is tailor-made for working with a MySQL database. What if you switch?

PDO, or PHP Data Objects, provides a more powerful API that doesn't care about the driver you use; it's database agnostic. Further, it offers the ability to use prepared statements, virtually eliminating any worry of SQL injection. Check out the range of PDO scripts and apps on Envato Market to get an idea of what's possible.


How?

When I was first learning about the PDO API, I must admit that it was slightly intimidating. This wasn't because the API was overly complicated (it's not) - it's just that the old myqsl API was so dang easy to use!

Don't worry, though; follow these simple steps, and you'll be up and running in no time.

Connect

So you already know the legacy way of connecting to a MySQL database:

With PDO, we create a new instance of the class, and specify the driver, database name, username, and password - like so:

Don't let that long string confuse you; it's really very simple: we specify the name of the driver (mysql, in this case), followed by the required details (connection string) for connecting to it.

What's nice about this approach is that, if we instead wish to use a sqlite database, we simply update the DSN, or "Data Source Name," accordingly; we're not dependent upon MySQL in the way that we are when use functions, like mysql_connect.

Errors

But, what if there's an error, and we can't connect to the database? Well, let's wrap everything within a try/catch block:

That's better! Please note that, by default, the default error mode for PDO is PDO::ERRMODE_SILENT. With this setting left unchanged, you'll need to manually fetch errors, after performing a query.

Instead, a better choice, during development, is to update this setting to PDO::ERRMODE_EXCEPTION, which will fire exceptions as they occur. This way, any uncaught exceptions will halt the script.

For reference, the available options are:

  • PDO::ERRMODE_SILENT
  • PDO::ERRMODE_WARNING
  • PDO::ERRMODE_EXCEPTION

Fetch

At this point, we've created a connection to the database; let's fetch some information from it. There's two core ways to accomplish this task: query and execute. We'll review both.

Query

Though this works, notice that we're still manually escaping the user's data with the PDO::quote method. Think of this method as, more or less, the PDO equivalent to use mysql_real_escape_string; it will both escape and quote the string that you pass to it. In situations, when you're binding user-supplied data to a SQL query, it's strongly advised that you instead use prepared statements. That said, if your SQL queries are not dependent upon form data, the query method is a helpful choice, and makes the process of looping through the results as easy as a foreach statement.

Prepared Statements

In this example, we're using the prepare method to, literally, prepare the query, before the user's data has been attached. With this technique, SQL injection is virtually impossible, because the data doesn't ever get inserted into the SQL query, itself. Notice that, instead, we use named parameters (:id) to specify placeholders.

Alternatively, you could use ? parameters, however, it makes for a less-readable experience. Stick with named parameters.

Next, we execute the query, while passing an array, which contains the data that should be bound to those placeholders.

An alternate, but perfectly acceptable, approach would be to use the bindParam method, like so:

Specifying the Ouput

After calling the execute method, there are a variety of different ways to receive the data: an array (the default), an object, etc. In the example above, the default response is used: PDO::FETCH_ASSOC; this can easily be overridden, though, if necessary:

Now, we've specified that we want to interact with the result set in a more object-oriented fashion. Available choices include, but not limited to:

  • PDO::FETCH_ASSOC: Returns an array.
  • PDO::FETCH_BOTH: Returns an array, indexed by both column-name, and 0-indexed.
  • PDO::FETCH_BOUND: Returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound.
  • PDO::FETCH_CLASS: Returns a new instance of the specified class.
  • PDO::FETCH_OBJ: Returns an anonymous object, with property names that correspond to the columns.

One problem with the code above is that we aren't providing any feedback, if no results are returned. Let's fix that:

At this point, our full code should look like so:

Multiple Executions

The PDO extension becomes particularly powerful when executing the same SQL query multiple times, but with different parameters.

Once the query has been prepared, it can be executed multiple times, with different parameters. The code above will insert two rows into the database: one with a name of "Kevin," and the other, "Steven."


CRUD

Now that you have the basic process in place, let's quickly review the various CRUD tasks. As you'll find, the required code for each is virtually identical.

Create (Insert)

Update

Delete

Object Mapping

One of the neatest aspects of PDO (mysqli, as well) is that it gives us the ability to map the query results to a class instance, or object. Here's an example:


Closing Thoughts

Bottom line: if you're still using that old mysql API for connecting to your databases, stop. Though it hasn't yet been deprecated, in terms of education and documentation, it might as well be. Your code will be significantly more secure and streamlined if you adopt the PDO extension. Check the PDO items on Envato Market to see what you can do.

Tags:

Comments

Related Articles