pdo

...now browsing by tag

 
 

Test Database Connectivity in PHP with PDO

Tuesday, August 19th, 2008

Testing connectivity to a database can be achieved a few different ways in PHP. Today we’ll take a quick look at a feature called PHP Database Objects (PDO). PDO is defined by php.net as:

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.

Now, on to how this bad boy works.

As with anything, we must start by assigning various variables. Similar to other methods of connecting, we will assign variables for the mysql connection host, database, username, and password.

// Assign variables for connecting to MYSQL Host
$dsn = 'mysql:host=localhost;dbname=mydatabase;';
$user = 'user';
$password = 'password';

In other ways, we could break it down into more variables:

$db_host = 'localhost';
$db_name = 'mydatabase';
$user = 'user';
$password = 'password';
$dsn = 'mysql:host=$db_host;dbname=$db_name;';

From there we will move on to a try catch statement using the PDO class to create a<strong> new PDO()</strong>. We will use our trust try/catch statement to test the connection and report any errors that may occur.

// Test the connection, alert if fails - very similar to C# in a sense
try
{
$sqlconn = new PDO($dsn, $user, $password);
//echo 'success';<img class="btnimage" onclick="formattext('text', 'outdent', '')" src="http://www.bobbyhash.com/wysiwyg/kevinrte/images/outdent.png" alt="" width="25" height="24" />
}

We will use $e as the exception / what our event will argue.

catch (PDOException $e)
{
echo 'Connection failed: ' .$e->getMessage();
}

As you can see it is a simple process. Set the variables, then utilize a try/catch statement to make the PDO request / handle the error.

And now for the unmolested code: Enjoy!

// Assign variables for connecting to MYSQL Host
$dsn = 'mysql:host = localhost;dbname=litebox;';
$user = 'user';
$password = '';

// Test the connection, alert if fails - very similar to C# or
//any other try/catch in a programming language in a sense
try
{
$sqlconn = new PDO($dsn, $user, $password);
//echo 'success';
}
catch (PDOException $e)
{
echo 'Connection failed: ' .$e->getMessage();
}