PDO

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:

Save & refresh browser:

sqlite 

sqlite2

mysql

 

 

DSN syntax:

database_type:host_location;database_name;

 

A simple connection could then be made using:

 

 

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,
PRIMARY KEY ('id')
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ; 

 

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:

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