0

How can I catch and ignore errors when connecting to a database and display a simple text message instead?

My connection looks like this:

$connection = mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);

If the connection fails I want it simply to echo "Error connecting to the database" instead of the big error box.

EDIT:

Although error_reporting(0) did work, what worked better was just putting '@' in front of mysqli_connect:

$connection = @mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);
    if (!$connection) {
        $connection_status = 'Connection to database failed';
    } else {
        $connection_status = null;
    }

?>
<?php echo $connection_status; ?>
1
  • What big error box...? Commented May 22, 2016 at 20:25

3 Answers 3

4

Taken from the documentation of mysqli_connect:

Examples

Example #1 mysqli_connect() example

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

mysqli_connect:

$connection = mysqli_connect($dbhost, $dbuser, $dbpw, $dbname);
if (!$connection)
{
    error_reporting(0);
    die("Error: Unable to connect to MySQL." . PHP_EOL);
}

To disable "big error boxes" (I assume standart messages?), write error_reporting(0); above this.

2 Comments

the error_reporting(0); does work, but is there anyway to only use error_reporting(0) for the connection? Turn them back on afterwards?
Yes, you can do something like in my edit. If the if clause is true, then error_reporting() stays the same as default (or previously declared).
1

You may set your custom handler for errors

register_shutdown_function("shutdownHandler");
function shutdownHandler()
{
    if (!is_null($e = error_get_last())).
    {
        echo $e['message'];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.