Timothy Fisher Timothy Fisher - 1 year ago 81
SQL Question

PHP - If no MySQL Connection then display simple message

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.


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; ?>

Answer Source


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download