Database Login Script - PDO

If there’s any improvements that can be made to the following script please let me know.

[php]
// Create URI for connecting to server
$dataSourceName = “mysql:host=$dbIPAddress;dbname=$dbName”;

// Create Server Connection Object
try {
$dbObject = new PDO($dataSourceName, $webServerUsername, $webServerPassword);
return $dbObject;
}
// If something breaks above, catch the thrown exception
// and hope some other program including this script outputs to the browser.
catch (PDOException $errorData) {
$errorMessage = $errorData ->getMessage();
$dbDebugMsg .= <<<DEBUG

Debug Message: Connection to $dbName @ $dbIPAddress has failed.

Details: $errorMessage

DEBUG; return $dbDebugMsg; } [/php]

Right now you are only displaying any errors to the user which is a security risk and doesnt do much good unless you are the user. You could could log and or email errors and then just display a generic error message to the user or “turn on” debugging and display the full errors for yourself. I include the following for my “Catch”

[php]catch (PDOException $e)
{
include_once(’…/config/pdo_catch_error.php’);
}[/php]

[php]<?php

$error_msg = $e->getMessage() . ’ in ’ . $e->getFile() . ’ on line ’ . $e->getLine();

if (DEBUG == 1)
{
echo ‘

’.$error_msg.’
’;
echo ‘
’;
echo ‘’.$stmt->debugDumpParams().’’;
echo ‘
’;
} //DEBUG == 1

//Email Error - suppressed error message to user with @ if no mail server.
if (EMAIL_ERROR == 1)
{
@error_log(“ERROR: $error_msg\n”, 1, “$email_admin”, “From: $email_from”);
} //EMAIL_ERROR == 1

// Write error to log
if (LOG_ERROR == 1)
{
error_log("$mysql_datetime|$error_msg\r\n", 3, “$errorlog_path”);
} //LOG_ERROR == 1

die(‘

Fatal Error! Admin has been notified
’);
?>[/php]

Ahh ok. If an error is encountered, I can use configuration run-time constants to flag which actions should be done based on a particular configuration. Can those constants be included through a separate include, or must I have them in the same file?

The constants can be set anywhere, but I have all configurable options in one included config file.

Sponsor our Newsletter | Privacy Policy | Terms of Service