PHP try/catch and fatal error

前端 未结 6 1843
庸人自扰
庸人自扰 2020-12-10 01:01

I\'m using the following script to use a database using PHP:

try{
    $db = new PDO(\'mysql:host=\'.$host.\';port=\'.$port.\';dbname=\'.$db, $user, $pass, $o         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 01:48

    I will not report what has already been written about testing if $db is empty. Just add that a "clean" solution is to artificially create an exception if the connection to the database failed:

    if ($db == NULL) throw new Exception('Connection failed.');
    

    Insert the previous line in the try - catch as follow:

    try{
    
        // This line create an exception if $db is empty
        if ($db == NULL) throw new Exception('Connection failed.');
    
    
        $query = $db->prepare("INSERT INTO users (...) VALUES (...);");
        $query->execute(array(
            '...' => $...,
            '...' => $...
        ));
    }
    catch(Exception $e){
        $GLOBALS['errors'][] = $e;
    }
    

    Hope this will help others!

提交回复
热议问题