2

所以我正忙着转移到 PDO(是的,我仍然是这样的老式 mysql 驱动程序)而且我以前从未使用过异常。我下面的代码是基于我迄今为止所理解的。我需要它的应用程序将创建 3 个单独的数据库连接,其中 2 个是 mysql 和 1 个 mssql(因此是 if else 类型)。

问题是,即使我提供了不正确的连接值,它仍然会处理并继续执行脚本,并完全跳过“catch”,就好像没有错误一样。我知道基础应该是:

 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;
    }
}
4

2 回答 2

0

发现了问题,这是我创建 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']);
于 2012-06-05T09:52:19.120 回答
0

我只是在这里猜测,但要从构造函数接收 PDO 异常,您可能必须在new调用中传递属性:

new PDO($dsn, $user, $password, array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));

更新

刚刚测试过,但即使没有传递属性,它也会引发异常。

于 2012-06-05T10:01:10.803 回答