如果数据库脱机,如何防止MySQLi崩溃PHP脚本

I have the following scenario:

I have a script that conencts to a remote database, and all works good unless the remote database is offline or the server is offline.

If database/server goes offline, the script uses long time to execute, what would be the best way to check if db connection was successfull before executing the SQL?

class remote_db{

    public $db;

    public function __construct(){

        $this->db = new mysqli("127.0.0.1","usr","pw","database");
        $this->db->set_charset("utf8");
    }
}


$remote_db = new remote_db();
if($remote_db){ echo 'hello world';}

There's no reason to check if it's online or not before running a query, since between the time you check, and the time you run the query, it might have gone offline. So simply run the query, and check for error afterwards, as you would normally do:

$r = $db->query('...');
if ($r === false) throw new Exception('error running query');

Also check for errors when you create the connection:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

You can also change the timeout property to reduce the waiting time:

$db->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5); // Wait for 5 seconds max

I suppose I finally managed to get what you mean under "crashing".

It seems your code structure is spaghetti, where HTML is intermixed with database stuff, and so on error it shows an incomplete, torn out design.

To prevent this, you have to structure your PHP application properly.

First of all, never output a single byte if not all database operations are not finished. To do so, split your PHP page into two parts: one is for the database interaction, that will collect all the data required to display; and another part, consists of HTML mostly, that is used to display the data.

After doing that, you will be able to show a dedicated error page, if error occurs during database stage.

Keep in mind that catching every single possible error is mission either highly inefficient and at the same time impossible: you simply cannot foresee and handle every error that may happen.

Instead, just make a simple code that will show a generalized error page in case of any error. To do so, setup an error handler like this (the code is taken from my article The (im)proper use of try..catch):

set_error_handler("myErrorHandler");
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    error_log("$errstr in $errfile:$errline");
    header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
    echo "Server error. Please try again later");
    exit;
}