Connecting to MySQL With PDO Class


I’ll demonstrate a simple example on how to connect to MySQL using PHP’s PDO class. Just some of the benefits of PDO is that it’s fast and if you use the PDO::prepare() method it will prevent SQL injection attacks by calling the PDO::quote() method. The other pros is that there are several databases it will support. So let’s dive right into the code:

Fatal Error new PDO Instance

Just an important note that if you receive the following type of fatal error in your development environment:

Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[42000] [1049] Unknown database ”user”’ in C:Program FilesApache Software Stack trace: #0 C:Program FilesApache Software PDO->__construct(‘mysql:host=loca…’, ‘username’, ‘password’) #1 C:Program FilesApache Software db::getConnect() #2 C:Program FilesApache Software FoundationApache2.2htdocstesttrunkcodelogin1connect.php(6): MySqlDb->confirmUserPass(‘usertest’, ‘passtest’) #3 {main} thrown in C:Program FilesApache Software on line 30

Looks pretty messy and hard to decipher. When trying to decipher error code I usually look at the first error which led me to see why it was reporting an “Unknown database” when it was existing. The extra quotes also gave me a hint as to the problem. So I concluded the problem resulted in the placement of extra quotes around the values of host and/or dbname. The following will generate the previous error:

$db = new PDO(“mysql:host=’localhost’;dbname=’mysql'”, $username, $password);

So if you do not use variables then do not add the single quotes for the values of host and dbname. In other words, use the following code instead:

$db = new PDO(“mysql:host=localhost;dbname=mysql”, $username, $password);

This is a simple test to connect to your mysql database or any other support database. Just for your information if you wish to connect to PostgreSQL which is another popular and robust database use the following code in place of the line of instantiation:

$db = new PDO(“pgsql:dbname=pdo;host=localhost”, “username”, “password” );

If you’re in a development environment and wish to display your errors directly to the screen you can specify the errors displayed. You need to set your display_errors settings to ‘on’ in your php.ini file. So set your error attributes after instantiating the PDO class like so:


There are three types of error report settings for PDO::ATTR_ERRMODE:

PDO::ERRMODE_SILENT = error codes


PDO::ERRMODE_EXCEPTION = Throw exceptions

Here’s an example of implementing PDO::ATR_ERRMODE:

Don’t confuse this with the errors generated from the php setting of error_reporting. The errors from PDO::ATTR_ERRMODE apply to the sql query and its results. I’ll dive into the error settings and the different outputs of the php.ini error_reporting settings and PDO::ATTR_ERRMODE report settings in a future article.


Leave a Reply