Feeling magnanimous today, here's the function I use to connect:
function PDOConnect($l_dbname=NULL, $l_msg=null, $l_options=null)
{
if ($l_options == null)
{ // set my default options
$l_options = array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_FOUND_ROWS => true,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
}
if ($l_dbname == null)
$host="mysql:host=localhost;charset=utf8";
else
$host="mysql:host=localhost;dbname=$l_dbname;charset=utf8";
$uid = "xxx";
$pswd = "yyy";
try
{
$pdo = new PDO($host, $uid, $pswd, $l_options);
}
catch (PDOException $e)
{
if (strtoupper($l_msg) == "SHOWMSG")
echo "Fatal Error<br>Failed to connect to mysql via PDO. PDO Error msg is:<br>".$e->getMessage();
else
echo "Fatal Error<br>Possible bad dbname?<br>Failed to connect to database server. Sensitive error msg may be viewed with additional parm to call to PDOConnect(dbname,'showmsg')";
return false;
}
if (!$pdo)
return false;
else // all worked - return handle to pdo connection.
return $pdo;
}
This assumes that you will want the assoc array format returned from your queries. You can easily override that in your fetch calls if you need to do something different at that point.
Stick this in some 'php' folder outside of your web tree so that only php scripts (and not html/web pages) can see it. Then simply call it ONCE in your script by:
$pdo = PDOConnect($dbname);