本文介绍了如何关闭PDO错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用phpunit测试连接,我已经创建了error_reporting(0)并分配了PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,但是当我故意提供错误的信息时,它总是会转储错误消息,例如,如果我输入了错误的帐户,它显示

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' (using password: YES)

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

如何将其关闭?

$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
}

如果连接失败,

推荐答案

PDO::__construct将始终抛出PDOException.您对此无能为力.如果任何理智的应用程序都无法连接,或者应该有充分的理由解释为什么需要关闭连接上的异常,则应该抛出异常.

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.

示例:

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

这篇关于如何关闭PDO错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:33