2012-06-05 50 views
2

所以我很忙轉移到PDO(是的,我仍然是oldschool mysql驅動程序),我從來沒有使用過例外。我的代碼是基於我目前瞭解的。我的應用程序,我將需要這將創建3個單獨的數據庫連接,其中2個將是MySQL和1個mssql(因此,如果其他類型的話)。特別不好理解異常

的問題是,即使我提供連接不正確的價值觀,它仍然處理,並與腳本將繼續,並跳過「抓」完全,因爲如果沒有錯誤。據我所知,基本應該是:

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; 
    } 
} 
+1

你確定'$ cred ['errors']'被設置爲''exception''? –

回答

0

發現這個問題,這是一個語法問題上面我PDO反對創作,我有:

$handler = new PDO("mysql:host".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']); 

,它應該具有B- EEN:

$handler = new PDO("mysql:host=".$cred['credentials']['server'].";dbname=".$cred['credentials']['database'].", ".$cred['credentials']['username'].",".$cred['credentials']['password']); 
+2

並沒有拋出PDOException? –

0

我只是猜測這裏,但接收來自構造一個PDO異常時,您可能要通過屬性在new電話:

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

更新

剛剛測試過,但即使沒有傳遞該屬性,也會拋出異常。