How to connect to MySQL using PDO

  1. Example
  2. Credentials exlained
  3. Connection options explained
  4. Creating the connection
  5. Don'ts
  6. Accessing the newly created connection
  7. Comments (6)

In this example we will learn how to properly connect to Mysql database using PDO. It is based on the information provided in the main article on PDO but with additional explanations.

Surprisingly, there is no single state-of-the-art connection example in the PHP manual. Instead, different connection options are discussed in different chapters, which makes it hard for the learner to get a single robust example that is ready to use. Below you will find such an example, as well as the explanation of all the options used.

Example

$host '127.0.0.1';
$db   'test';
$user 'root';
$pass '';
$charset 'utf8mb4';

$options = [
    
PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    
PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset"$user$pass$options);

Credentials exlained

First of all we are defining variables that contain connection credentials. This set is familiar to anyone who were using the old mysql_connect() function, save for $charset may be, which was rarely used (although it should have been).

Connection options explained

Next we are creating an array with PDO options that are either critically important or just make your experience with PDO much better.

Creating the connection

Having all the options and credentials set, we can finally proceed to creating a connection. To do so we need to create an instance of PDO class for which we need to supply 4 parameters of which the first one, called "DSN" being most important.

DSN is a semicolon-delimited string, consists of param=value pairs, that begins from the driver name and a colon:

      mysql:host=localhost;dbname=test;port=3306;charset=utf8
driver
^    ^ colon         ^param=value pair    ^semicolon  

Note that it's important to follow the proper format - no spaces or quotes or other decorations have to be used in DSN, but only parameters, values and delimiters, as shown in the manual.

Beside DSN, we are using $user, $pass and $options variables defined above.

Don'ts

Beside things that you should do, there are always things that you should do not. Some of them we will discuss below.

Accessing the newly created connection

There is one thing that makes PDO more complex than old mysql_connect related stuff. Although one was able to use mysql_query anywhere in the code, without taking care of the connection which was magically supplied by PHP, with PDO one should always make sure that once created PDO instance is available in each part of their script.

There are many different strategies to have this done, but mostly used are:


Related articles: