PDO catch PDOException fails on construction

前端 未结 2 421
情话喂你
情话喂你 2021-01-27 17:26

I\'ve seen variations of this code all over the place, including many S.O. posts:

class db extends PDO {

    public function __construct( $dbconf ) {
        $o         


        
相关标签:
2条回答
  • 2021-01-27 17:48

    The reason being is PDO::__construct only creates the object upon successful connection. So when you call the parent constructor and it fails your object doesn't exist anymore. You should use self::myerror() to access the error function statically in this case.

    0 讨论(0)
  • There shouldn't be myerror() function at all. A database layer scarcely need it's own error handler. And constructor have to be

    public function __construct( $dbconf ) {
        $dsn  = "mysql:";
        $dsn .= "host=".   $dbconf['dbhost'].";";
        $dsn .= "dbname=". $dbconf['dbname'].";";
        $dsn .= "port=".   $dbconf['dbport'].";";
        $dsn .= "charset=".$dbconf['dbcharset'];
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES '.$dbconf['charset'],
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT         => (bool)$dbconf['persist'],
        );
        parent::__construct($dsn, $dbconf['dbuser'], $dbconf['dbpass'],$options);
    }
    
    0 讨论(0)
提交回复
热议问题