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. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server
PDO has (among others) these unique features:
- PDO is a native C extension.
- PDO takes advantage of the latest PHP 5 internals.
- PDO uses buffered reading of data from the result set.
- PDO gives common DB features as a base
- PDO is still able to access DB-specific functions
- PDO can use transaction-based techniques
- PDO can interact with LOBS (Large Objects) in the database
- PDO can use prepared and executable SQL statements with bound parameters.
- PDO can implement scrollable cursors
- PDO has access to SQLSTATE error codes and has very flexible error handling
Making a connection using PDO
$db = new PDO ($dsn, $username, $password);
$db = new PDO(“mysql:host=localhost;dbname=library”, “petermac”, “abc123”);
Interaction with the database
$db->query(“UPDATE books SET authorid=4 WHERE pub_year=1982”);
PDO and prepared statements
PDO also allows for what are known as prepared statements. This is done with PDO calls in stages or steps. Consider the following code:
$statement = $db->prepare( "SELECT * FROM books");
$statement->execute();
// gets rows one at a time
while ($row = $statement->fetch()) {
print_r($row);
// or do something more meaningful with each returned row
}
$statement = null;