Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Use PDO extension in PHP for better database usage

Friday, September 21st, 2012 by Servage

Using PDO in PHP is a good way to ensure that your project is using a standard compliant and cross-database-platform compatible system. The PDO driver ensures that you can transport your code across multiple platforms, using different database servers.

PDO isn’t just a cross-platform driver that enables this platform-independence. It also provides a series of great functions to make database queries easier and faster to perform. Furthermore it helps securing queries against injection and manipulation with unwanted content or even hacking attempts. Check out the below example from the PHP documentation:

Example 1, question-mark references

$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();

First you have two regular variables $calories and $colour. They could contain anything, like user input, so we don’t trust them. Then you prepare a SQL statement with the PDO prepare method. It contains references to calories and color by question marks, which are then bound with the bindParam method, whereafter you execute the query. This is a neat way to generate standard SQL with protection against injection.

Example 2, named references

$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour'); $sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

In this second example the same variables are bound using names parameters inside the prepared query.

Read more in the PHP documentation.

Use PDO extension in PHP for better database usage, 5.0 out of 5 based on 3 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.