Alternatively, you can work with PDO and exceptions, which has the advantages of not disclosing too much information to users, yet still making that info available for you to log:
PHP Code:
<?php
include_once('localDB.php');
try {
$dbConn = localDB();
$query = $dbConn->prepare(...);
$query->execute(...);
foreach ($query as $row) {
...
}
} catch (PDOException $exc) {
error_log($exc);
header('Location: ...'); // This only works if nothing has been outputted.
// OR
include(...);
} ?>
You could also include scaffolding to print the exception (rather than redirect) when a variable is set or logged on as an admin. Be careful with this: the exception information includes the call stack. If the error happens when creating a PDO object, the username & password appear on the call stack.
localDB.php handles DB connections and bundles up credentials:
PHP Code:
<?php
function localDB($dbName='...') { // replace '...' with default DB name
static $db = array();
if (empty($db[$dbName])) {
$db[$dbName] = new PDO("mysql:host=localhost;dbname=$dbName", 'user', 'password');
}
$db[$dbName]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db[$dbName];
}
?>