Connecting with PDO

After creating a DSN, we are ready to connect to the database. This is done by creating a instance of the PDO Class. Three values are passed to the PDO Class, the DSN, the username and the password for access to the database.

<?php 
  $dsn = 'mysql:host=localhost;dbname=movies';
  $db = new PDO($dsn, 'root', 'root');

It always a good idea to add a try / catch block around the PDO connection to catch any potential errors that occur and help prevent any security issues.

<?php 
  try {
    $dsn = 'mysql:host=localhost;dbname=movies';
    $db = new PDO($dsn, 'root', 'root');
  } catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
  }

Finally, because the database connection will likely be required on multiple documents, it always best to store the connection to its own document that can be then included where needed.