Search code examples
phppdo

How to turn off PDO error message


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 give the wrong information on purpose, it always dump error message, for example, if I give the wrong account, it shows

PDOException: SQLSTATE[HY000] [1045] Access denied for user 'test'@'localhost' (us ing password: YES)

How to turn it off?

$options = array(
    PDO::ATTR_ERRMODE    => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_PERSISTENT => false,
);
$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8';

try {
    $this->dbh = new PDO($dsn, $config['username'], $config['password'], $options);
} catch (PDOExeception $e) {
    // Do something
}

Solution

  • 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");
    ?>