Using PHP Data Objects (PDO)

Connections are established by creating instances of the PDO base class. It doesn’t matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source and optionally for the username and password. Example as :

1. Connecting to MySql :

<?php
    $dbh = new PDO('mysql:host=localhost;dbname=test', "username", "password");
?>

2. Executing Query :

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', "username", "password");
    foreach($dbh->query('SELECT * from car') as $row) {
        var_dump($row);
    }
    $dbh = null; // setting connection to null
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception.