What is PHP Data Object?

Posted on

PHP Data Object is a Database Connection Abstraction Library for PHP 5.

What is PDO?

  • a PHP5 extension written in a compiled language (C/C++)
  • a Lightweight DBMS connection abstract library (data access abstraction library)

Why PDO?

  • Support great number of database systems supported by PHP
  • You don’t need rewriting of many line code for each database. Just write one and run anywhere
  • Speed. PDO written in compiled language, PHP libraries (ADOdb, PEAR DB) written in an interpreted language
  • Your software more easy to install. Do not need third party software

Whenever you need PDO?

  • You need portable application that support many database system
  • You need speed


we test to connect to database. We use mysql server. Before test, please create a database named “test”. Then create table “books” with query like this:

1 CREATE TABLE `books` (
2   `id` int(11) NOT NULL auto_increment,
3   `title` varchar(150) NOT NULL,
4   `author` varchar(150) NOT NULL,
5   `description` varchar(255) NOT NULL,
6   `on_sale` tinyint(1) NOT NULL,
7   PRIMARY KEY  (`id`)
8 );

Following query for sample data:

1 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (1, 'PHP AJAX', 'Andreas', 'This is good book for learning AJAX', 1);
2 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (2, 'PHP Eclipse ', 'George', 'Nice book', 0);
3 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (3, 'PHP Prado', 'Junyian', '-', 1);
4 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (4, 'PHP Zend Framework', 'Ozulian', 'great', 0);
5 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (5, 'PHP Web Services', 'Bobi', '', 0);
6 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (6, 'PHP API', 'Hugo', '', 1);
7 INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (7, 'PHP SEO', 'Monteo', '', 1);

Now, this is sample connection to mysql database:

01 <?php
02 $host   = "localhost";
03 $db = "test";
04 $user   = "root";
05 $pass   = "admin";
07 $conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
09 $sql = "SELECT * FROM books";
10 $q   = $conn->query($sql) or die("failed!");
11 while($r = $q->fetch(PDO::FETCH_ASSOC)){
12   echo $r['title'];
13 }
16 ?>

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s