Skip to content

Instantly share code, notes, and snippets.

@SkypLabs
Last active May 25, 2018 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SkypLabs/dd1fa68b9c8e4e76366206513da2f32c to your computer and use it in GitHub Desktop.
Save SkypLabs/dd1fa68b9c8e4e76366206513da2f32c to your computer and use it in GitHub Desktop.
Sample code to show how to handle database error messages in PHP according to the current user's status - See https://blog.skyplabs.net/2011/03/19/afficher-les-erreurs-sql-de-php-seulement-aux-personnes-concernees/ (French)
<?php
// Connection variables.
$db_type = "";
$db_host = "";
$db_user = "";
$db_password = "";
$db_database = "";
// We test the connection with the database.
try
{
$db = new PDO($db_type.":host=".$db_host.";dbname=".$db_database, $db_user, $db_password);
}
catch (Exception $e)
{
// If the current user has the administrator status, we display the
// complete error message.
if (isset($_SESSION['status']) && $_SESSION['status'] == 'admin')
die("Error : " . $e->getMessage());
// Else, we display a generic error message with no details.
else
die("Error : Impossible to establish the connection with the database.");
}
// Used to handle database error messages.
function mySqlError($db)
{
// If the current user has the administrator status, we display the
// complete error message.
if (isset($_SESSION['status']) && $_SESSION['status'] == 'admin')
print_r($db->errorInfo());
// Else, we display a generic error message with no details.
else
echo "Error : Sorry, an SQL error has occured.";
}
?>
<?php
$exemple_of_query = $db->prepare("INSERT INTO table VALUES (:var1, :var2, :var3)");
$exemple_of_query->execute(array('var1' => $var1, 'var2' => $var2, 'var3' => $var3))
or die(mySqlError($db));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment