Search code examples
mysqldatabaseerror-handlinginnodb

How to forward a connection failed MySQL to a error page (500)


We made a simple php webpage with a InnoDB tabel, to monitor if InnoDB goes down.

When InnoDB / Mysql goes down we get a error: Connection failed: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory")

But we wanna forward this to a custom error. Lik: InnoDB IS DOWN!!!

Any suggestions how we can do this?

<?php
$servername = "localhost";
$username = "root";
$password = "**************";
$dbname = "innodb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT status FROM monitoring";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "De status van InnoDB is:  " . $row["status"]. "<br>";
    }                                                              
} else {
    echo "0 results";
}
$conn->close();
?>

Solution

  • It's simple, use something like this

    <?php
    // Configuration of database
    
    // Check connection
    if ($conn->connect_error) {
        // die("InnoDB IS DOWN");
        // OR
        echo "<p>InnoDB IS DOWN</p>";
        exit();
    }
    
    // Rest of your code
    

    OR you may include an HTML page as well in the IF condition if ($conn->connect_error) like:

    // Check connection
    if ($conn->connect_error) {
        include 'error_page.html';
        exit();
    }
    
    // Rest of your code