PDO Tutorial

Written by Lucas, on Thu 03 January 2008, 23:41:51

Because the fate of the mysql_* functions are uncertain in the next release of PHP, moving to the new data-access api of PHP, PDO, wouldn't be a bad idea. :)

In my opinion it's a great idea to remove the mysql_* functions and use something more object oriented, and PDO is the perfect solution for that. It supports multiple database engines, although you'll need to correct PDO drivers for each database engine.

In this post I'll explain how to enable PDO on your PHP installation, and how to use it. :) Click read more for the tutorial :)

Before we can use it, we need to enable the extension in php.ini, so open that file in your favorite editor and search for the extension part, which you can recognise when you see some lines like this:
  1.  
  2. extension=php_xxx.dll
  3.  


At the end of that section add:
  1.  
  2. extension=php_pdo.dll
  3.  


But with only pdo you can't do much, you'll need the database drivers for PDO. Almost all databases are supported so pick the one you're using:
  1.  
  2. extension=php_pdo.dll
  3. extension=php_pdo_firebird.dll
  4. extension=php_pdo_informix.dll
  5. extension=php_pdo_mssql.dll
  6. extension=php_pdo_mysql.dll
  7. extension=php_pdo_oci.dll
  8. extension=php_pdo_oci8.dll
  9. extension=php_pdo_odbc.dll
  10. extension=php_pdo_pgsql.dll
  11. extension=php_pdo_sqlite.dll
  12.  


Installation on Linux
Make sure you have the following packages installed (These are available in synaptic):
php5-dev
php-pear

You'll need the 'pecl' command. Open up a terminal and enter:
sudo pecl install pdo


PECL will automaticly download, compile and install the PDO extension. The only thing you need to do is add it to php.ini.

You'll also need a PDO driver, so still in terminal, enter:
sudo pecl install pdo_driver_name

for example:
sudo pecl install pdo_mysql

Now add it to php.ini:

  1.  
  2. extension=pdo.so
  3. extension=pdo_mysql.so
  4.  


And you're finished. :)

Connecting

Connecting is easy:
  1.  
  2. try
  3. {
  4.     $conn = new PDO('mysql:host=localhost;dbname=your_db_name;', 'user', 'pass');
  5. }
  6. catch(PDOException $e)
  7. {
  8.     die("Could not connect to db: ".$e -> getMessage());
  9. }
  10.  


the constructor accepts three parameters, one of them is optional. The first is the connection string, it contains the database engine (mysql), the host, and the database name. The second parameter is the database username and the last one the password. Not much special is it? :)

The connection string may differ if you're using an other database engine.

If you're Database server runs on a different port than the default one, you can add another field to the connection string named 'port':

  1.  
  2. try
  3. {
  4.     $conn = new PDO('mysql:host=localhost;port=3307;dbname=your_db_name;', 'user', 'pass');
  5. }
  6. catch(PDOException $e)
  7. {
  8.     die("Could not connect to db: ".$e -> getMessage());
  9. }
  10.  


One thing to keep in mind: if it can't connect to the database server, it will throw an Exception, and the default behaviour to handle exceptions is to display a message and a stack trace. And in the stack trance are often parts of the arguments passed with it included. So it will probably reveal your database username and password. It's your responsibility to catch that exception and only display the message.

Executing queries
PDO makes a distinction between queries which do return rows (SELECT etc), and queries which don't return rows (INSERT, UPDATE, DELETE, etc).

For queries which do return rows you use the function query();
  1.  
  2. $result = $conn -> query("SELECT * FROM table");
  3.  


The query function will return another object representing the result.

  1.  
  2. <?php
  3. $result = $conn -> query("SELECT * FROM table");
  4.  
  5. echo "Number of rows: ".$result -> rowCount()."<br />";
  6. while($row = $result -> fetch())
  7. {
  8.     echo "<pre>", print_r($row), "</pre>";
  9. }
  10.  

In this piece of code we select every row from table, and echo the number of rows, and then iterate through all the rows, print_r()'ing the row data.

You can also use the foreach statement:

  1.  
  2. <?php
  3. $result = $conn -> query("SELECT * FROM table");
  4.  
  5. echo "Number of rows: ".$result -> rowCount()."<br />";
  6. foreach($result as $row)
  7. {
  8.     echo "<pre>", print_r($row), "</pre>";
  9. }
  10.  


To view all functions which are available at the result object view this page, and scroll a bit down for PDOStatement class methods :)

If you want to execute a query which doesn't return rows, you'll need to use the exec() function. In contrast to the query() function, exec() doesn't return an result object, but instead the number of rows affected by the query.

  1.  
  2. $affected = $conn -> exec('DELETE FROM table');
  3. echo "Deleted ".$affected." rows!";
  4.  


Prepared Statements
The most powerful feature of PDO. Prepared statements are a lot safer because the parameters used in queries are escaped automatically. Also it can be used to execute a lot of the same queries, in an easy way.

Here are some examples:
  1.  
  2. $statement = $conn -> prepare("DELETE FROM users WHERE name = ?");
  3. $statement -> execute(array($_GET['name']));
  4.  


Notice the '?' in the query. This character is automatically replaced by PDO, including quotes and escaped and all, so you don't need to worry about SQL Injection or something anymore.

  1.  
  2. $statement = $conn ->prepare("INSERT INTO table (name, age) VALUES (:name, :age)");
  3.  
  4. $name = "";
  5. $age = 0;
  6.  
  7. $statement -> bindParam(':name', $name);
  8. $statement -> bindParam(':age', $age);
  9.  
  10. $name = "Lucas";
  11. $age = 17;
  12. $statement -> execute();
  13.  
  14. $name = "Pete";
  15. $age = 23;
  16. $statement -> execute();
  17.  


This snippet inserts 2 rows, one row with the name 'Lucas', and age 17, and the other row with name 'Pete' and age 23.

As you can see wee can execute the same query multiple times with different values, by just changing the variable.

Conclusion

I hope you learned the basics of using PDO. I would highly recommend using prepared statements, because they're a lot safer, and add extra functionality. Of course PDO offers a lot more, but you can view that in the official documentation located here.

Tag Tags: php oop PDO
Comments (4)