PHP Introduction | Database Access with PDO | Creating a PDO Object

Loading the Driver

Now let us actually access MySQL with PDO. To use PDO, the driver program for PDO must be loaded in PHP. Driver loading is configured in the php.ini file. In XAMPP, this file is in the php folder inside the XAMPP installation folder.

extention=php_pdo.dll
extention=php_pdo_XX.dll

Search php.ini for entries like these. The XX part specifies the database type. For MySQL, you should find entries that load the two DLL files php_pdo_mysql_mysqlnd.dll and php_pdo_mysql_libmysql.dll. If a semicolon (;) indicating a comment appears at the beginning of the line, remove it. After restarting the server, the driver can be loaded.

In current XAMPP 1.7.x versions, the MySQL driver is loaded by default, so you do not need to edit php.ini.

Summary of Basic PDO Access

Now let us summarize database access with PDO. The first thing to do is create a PDO object.

$variable = new PDO(server specification, user name, password);

Create it in this form. The first argument specifies the database, and the second and third arguments specify the user name and password used for access. The key point is the first argument. Write it in the following form.

"database type:host=host;dbname=database;charset=encoding"

For MySQL, specify "mysql" as the database type. When accessing a database named mysampledata on localhost, as in this example, it looks like this.

"mysql:host=localhost;dbname=mysampledata;charset=utf8"

This creates a PDO object for accessing a specific database through MySQL. After that, you only need to call the required methods on this object.

There is one more thing to note when creating a PDO object: an exception may occur. If a problem occurs while accessing a database with PDO, a PDOException is thrown. Therefore, new PDO and the database access are usually written in the following form.

try {
    $variable = new PDO(server specification, user name, password);
    ... call methods on $variable to access the database ...
} catch (PDOException $e) {
    ...... processing when an exception occurs ......
}

After that, the methods you call and the way you handle values returned from the database will depend on what you want to do with the database.