PHP Data Objects, provide database access standardisation (some call this an access abstraction layer) that allows portable code to be used across multiple databases and platforms. Meaning, the same functions to perform queries and fetch data are used regardless of the type of database being used.


3 classes:

  • PDO class maintains database connection
  • PDOStatement class, handles SQL queries
  • PDOException class, provides error handling


PDO class

requires 3 pieces of information:

  • database location
  • username
  • password


The database location is in the form of a DSN (Data Source Name) which conforms to a specific format and is slightly different for each type of database.


To determine the available database drivers on your system:

foreach(PDO::getAvailableDrivers() as $driver)
    echo $driver.'<br />';

Save & refresh browser:






DSN syntax:



A simple connection could then be made using:

$dsn = "mysql:host=localhost;dbname=test_db";
$pdo = new PDO($dsn, $username, $password, $opts);



For the purpose of these PDO articles, I will be using my motogp database and the riders table, as follows:


CREATE TABLE 'riders' (
'id' mediumint(8) NOT NULL AUTO_INCREMENT,
'name' varchar(25) COLLATE utf8_unicode_ci NOT NULL,
'team' varchar(25) COLLATE utf8_unicode_ci NOT NULL,
'points' mediumint(8) NOT NULL,
'status' varchar(28) COLLATE utf8_unicode_ci NOT NULL,


INSERT INTO 'riders' ('id', 'name', 'team', 'points', 'status') VALUES
(1, 'Dani Pedrosa', 'Honda', 136, 'Factory'),
(2, 'Jorge Lorenzo', 'Yamaha', 127, 'Factory'),
(3, 'Marc Marquez', 'Honda', 113, 'Factory'),
(4, 'Cal Crutchlow', 'Yamaha', 87, 'Factory'),
(5, 'Valentino Rossi', 'Yamaha', 85, 'Factory'),
(6, 'Andrea Dovizioso', 'Ducati', 65, 'Factory'),
(7, 'Stefan Bradl', 'Honda', 51, 'Factory'),
(8, 'Nicky Hayden', 'Ducati', 50, 'Factory'),
(9, 'Alvaro Bautista', 'Honda', 47, 'Factory'),
(10, 'Aleix Espargaro', 'ART', 44, 'CRT');


We'll now connect to the above database table and perform a simple query:

	$host = 'localhost';
	$dbname = 'motogp';
	$dsn = "mysql:host=$host;dbname=$dbname";
	$username = "testing";
	$password = "secret";

	$dbh = new PDO($dsn, $username, $password);//database handle

	echo "Connected to the $dbname database<br>";

	$sqlQuery = 'SELECT * from riders';//select everything from the riders table

	foreach($dbh->query($sqlQuery) as $row) {
		echo $row['rider_name'] . " rides for " . $row['rider_team'] . "<br>";
	$dbh = null; //close connection

Save & refresh browser:

Connected to the motogp database
Dani Pedrosa rides for Honda
Jorge Lorenzo rides for Yamaha
Marc Marquez rides for Honda
Cal Crutchlow rides for Yamaha
Valentino Rossi rides for Yamaha
Andrea Dovizioso rides for Ducati
Stefan Bradl rides for Honda
Nicky Hayden rides for Ducati
Alvaro Bautista rides for Honda
Aleix Espargaro rides for ART

Leave a Reply