PDO Database Connection

Using PDO to Connect To mySQL

When using mySQL for PHP applications, you normally connect to a database using a function. Some popular methods are mysql_connect(), mysqli_connect()and PDO objects. This simple example will explain how to do it using PDO.

PDO has all sorts of advantages, such as binding parameters to a query so that mySQL handles the variable separately.

The following examples explain how to connect with PDO and return it from a function.

File: _pdo.php The Function

The function below creates a new object instance and return the $PDO object for making our desired queries. Above the function, the code is used to not allow direct access to the file.

Asides from knowing more code and how it works is always better than just winging it, the only editing you would need to make to the file is to provide your database name, database user and database user password. These values are created when you create a new mySQL user with the command line, or tool like Cpanel.

if(!defined('my_pdo')) {
    die('Direct access not permitted');

function PDO_Connect()
    $user = 'databaseuser';
    $pass = 'databaseuserpassword';
    $PDO = new PDO('mysql:host=localhost;dbname=mydatabasename', $user, $pass);
    return $PDO;

File Connection Calling the Function

The file below defines a constant called my_pdo that will allow you to access the _pdo.php file. Remember from the last example that it is located above the function.

After that, the _pdo.php file is included. Finally, the function is called and the database object is returned. The database object, $PDO is what will be used for making all database queries.

define('my_pdo', true);
include "_pdo.php";
$PDO = PDO_Connect();