Try & catch pdo close database connection

前端 未结 2 520
遇见更好的自我
遇见更好的自我 2021-02-06 19:50
try{
    //PDO CONNECT DB, $db

}catch(PDOException $e){die(\"ERROR\"));}

I have a query user PDO connect to database.

I use try & catch, m

相关标签:
2条回答
  • 2021-02-06 20:33

    No, it is not necessary in php. When your php process finished, the connection will be closed too.

    0 讨论(0)
  • 2021-02-06 20:36

    As a matter of fact, you shouldn't die() at all

    Until you learn how to use try and catch properly, you shouldn't use this statement. It is not intended for echoing "ERROR". It has totally different purpose.

    If you want to echo silly "ERROR" in case of an erroneous query, you have to do it properly.
    Namely,

    • send appropriape HTTP header
    • log the error to notify a developer of the problem
    • show whatever error message to the client
    • have all this stuff done in one place, not repeated for every query

    to do this, you have to set up an exception handler:

    set_exception_handler('myExceptionHandler');
    function myExceptionHandler($e)
    {
        header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
        error_log($e->getMessage().". Trace: ".$e->getTraceAsString());
        echo "ERROR";
        exit;
    }
    

    put this code in your bootstrap/config file and quit wrapping every query into try-catch.

    0 讨论(0)
提交回复
热议问题