How to turn off PDO error message

前端 未结 1 1365
陌清茗
陌清茗 2021-01-24 04:15

I am trying to use phpunit to test connection, I already make error_reporting(0) and assign PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT, but when I giv

相关标签:
1条回答
  • 2021-01-24 04:59

    PDO::__construct will always throw a PDOException if the connection fails. There is nothing you can do about that. Any sane application should throw exception if it fails to connect or maybe you have good reason to explain why you need to turn off exception on connections.

    Beside the connection It will work on others transactions.

    Example:

    <?php
    $options = array(
        PDO::ATTR_ERRMODE    => PDO::ERRMODE_SILENT,
        PDO::ATTR_PERSISTENT => false,
    );
    $dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8';
    try {
        //THIS WILL THROW EXECPTION IF FAILED, NO MATTER WHAT ERROR MODE YOU SET
        $this->dbh = new PDO($dsn, $config['username'], $config['password'], $options);
    } catch (PDOException $e) {
        // Do something
    }
    
    //JUST SILENT THIS  WILL NOT CAUSE EXCEPTION
    $dbh->query("SELECT badColumn FROM wrongTable");
    ?>
    
    0 讨论(0)
提交回复
热议问题