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:
<?php
/*** 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();
}
?>