Connecting to PDO as an object

Moving from procedural with mysql_connect, etc to PDO objects should be an easy transition.  It’s so much faster and reliable, too.  The “mysql” library in PHP will soon be deprecated, so you hold-outs won’t have a choice.  It’s actually less code to write and get whole queries into resulting arrays much faster.  Trust me!

Here’s how you instance a new PDO object and connect to your MySQL database through PDO:


/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username';

/*** mysql password ***/
$password = 'password';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
catch(PDOException $e)
echo $e->getMessage();


About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *