PDO is an awsome database interface extension for PHP. It's written in C and are included in the PHP core.
It's easy to use and is much more robust against SQL-injections. This is because you explicit define what is a value.
Here are some examples of how to use PDO.
Initalize the PDO object.
try {
$pdo = new PDO(
"mysql:dbname=db;host=localhost", 'user', 'pass',
array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::FETCH_ASSOC => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
}
catch (PDOException $e) {
die ($e->getMessage());
}
PDO::ATTR_EMULATE_PREPARES => true
PDO emulates prepared statements instead of sending them to the sql driver. With the MySQL driver, this will increase speed.
PDO::FETCH_ASSOC => true
Fetching rows from a query will only return a set of associative keys. By default you get a set of numerical keys too, which are rarely used.
If you fetch 'SELECT firstname, middlename, surname' in $row, you will get $row['firstname'], $row[0], $row['middlename'], $row[1],
$row['surname'] and $row[2]. PDO::FETCH_ASSOC will not return the numerical keys.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
Makes an exception on errors, which makes it nice and easy to handle errors.
Here's an example of how to make a standard query with parameters.
You don't need to escape the inputs with mysql_real_escape_string(), because PDO knows what is parameters and not.
(This is just and example, you don't want the users password as plain text in the database.)
$sql = "SELECT id FROM users
WHERE username = :user AND password = :pass";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':user', $_POST['username']);
$stmt->bindParam(':pass', $_POST['password']);
$stmt->execute();
$result = $stmt->fetch();
print $result['id'];
When calling a static call without paramters you could just do:
$sql = 'SELECT username FROM users ORDER BY id DESC';
foreach ($pdo->query($sql) as $row) {
print $row['username'];
}
When dealing with classes. Pass the PDO-object with the constructor and make it protected.
class Foo {
protected $pdo;
function __contruct($pdo) {
$this->pdo = $pdo;
}
}
When you need to use SQL's "LIMIT" you need to explicit tell PDO that it is in fact integers we are inserting.
$stmt = $pdo->prepare("SELECT foo FROM bar LIMIT :offset, :hits");
$stmt->bindValue(':offset', (int) $offset, PDO::PARAM_INT);
$stmt->bindValue(':hits', (int) $hits, PDO::PARAM_INT);
This is explained more in detail here:
http://e-mats.org/2009/02/pdo-and-pdoparam_int/
Now go and explore PDO if you havn't already done so!