所以我正忙着转移到 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;
}
}