Php 非常不善于理解异常
所以我正忙着转向PDO(是的,我仍然是那种老式的mysql驱动程序),我以前从未使用过异常。我下面的代码是基于我到目前为止所理解的。我需要的应用程序将创建3个独立的数据库连接,其中2个是mysql,1个是mssql(因此是if-else类型) 问题是,即使我提供了不正确的连接值,它仍然处理并继续使用脚本,并完全跳过“捕获”,就好像没有错误一样。我理解,基本原则应该是:Php 非常不善于理解异常,php,exception,pdo,Php,Exception,Pdo,所以我正忙着转向PDO(是的,我仍然是那种老式的mysql驱动程序),我以前从未使用过异常。我下面的代码是基于我到目前为止所理解的。我需要的应用程序将创建3个独立的数据库连接,其中2个是mysql,1个是mssql(因此是if-else类型) 问题是,即使我提供了不正确的连接值,它仍然处理并继续使用脚本,并完全跳过“捕获”,就好像没有错误一样。我理解,基本原则应该是: try { if("condition" != "conditions") { throw
try {
if("condition" != "conditions") {
throw new Exception("Oops I did it again");
}
catch(Exceptions as e) {
echo $e->getMessage();
}
我也理解PDO将通过例外,因此我不必抛出,但它只是不起作用,请帮助我,并对我对这个概念的误解给予更多的监督:
// connect(): Connect to a database (MySQL):
private function connect($cred) {
$type = $cred['type'];
if($type == "mysql") {
try {
$handler = new PDO("mysql:host".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
if($cred['errors'] == 'exception') {
$handler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} elseif($cred['errors'] == 'warning') {
$handler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
} else {
$handler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
}
}
catch(PDOException $e) {
$this->informer("FATAL","An error has occured trying to connect to the connection (".$cred['name'].") -".$e->getMessage());
return false;
}
return $handler;
}
}
发现问题,在我的PDO异议创建过程中,这是一个语法问题,我有:
$handler = new PDO("mysql:host".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
应该是:
$handler = new PDO("mysql:host=".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
发现问题,在我的PDO异议创建过程中,这是一个语法问题,我有:
$handler = new PDO("mysql:host".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
应该是:
$handler = new PDO("mysql:host=".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']);
我在这里只是猜测,但要从构造函数接收PDO异常,您可能必须在
new
调用中传递属性:
new PDO($dsn, $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
更新
刚刚测试过,但即使没有传递属性,它也会抛出异常。我只是在这里猜测,但是要从构造函数接收PDO异常,您可能必须在
新建
调用中传递属性:
new PDO($dsn, $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
更新
刚刚测试过,但即使没有传递属性,它也会抛出异常。并且您确定
$cred['errors']
设置为'exception'
?并且您确定$cred['errors']
设置为'exception'
?并且没有抛出PDOException??并且没有抛出PDOException??