PDO (PHP Data Objects) - Starter Guide

Posted on

It may surprise you to hear, that using the mysql_connect() function in PHP has recently be marked as “old hat” coding because it’s slow in comparison with newer methods. A better alternative is PDO (PHP Data Objects), a lightweight method for accessing databases. Here is a quick overview to help you get started with PDO.

Reasons to use PDO

Connecting to a Database

Connecting to a database is pretty simple. Here is how to connect to a MySQL Database.

// Define the parameters
$host = 'localhost';
$dbname = 'my_database';
$user = 'mysql_username';
$pass = 'mysql_password';

try {
  // Call the PDO class.
  $db= new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
} catch(PDOException $e) {
  // If something goes wrong, PDO throws an exception with a nice error message.
  echo $e->getMessage();


Doing A Query

Again, doing a query is just as simple as:

$query = $db->query('SELECT * FROM `users` ORDER BY ID DESC;');
$result = $query->fetchAll(PDO::FETCH_ASSOC);

// $result will now contain an object of all the rows in the table 'Users'

However, if you are using user variables which may cause a SQL Injection you should bind the parameter to the query (see next example).

Binding a parameter to a query

$query = $db->prepare('SELECT * FROM `users` WHERE `ID` = :ID: AND `email` = :email: ORDER BY ID DESC LIMIT 0,1;');
$query->execute(array(':ID:' => '3', ':email:' => 'me@email.com'));
$result = $query->fetchAll(PDO::FETCH_ASSOC);

If you bind a parameter to a request, it will sterilize the input so that it will not cause a SQL Injection.

Useful Resources

PHP Manual: PHP Data Objects Nettuts+: Why you Should be using PHP’s PDO for Database Access


As of PHP 5.4 the MySQL extension will be softly deprecated. This means you really should start using PDO ASAP!