在使用PDO時,catch Exception有兩種用法
//資料庫連線失敗 try { $dsn = "mysql:host=localhost;dbname=eaaaaa"; $db = new PDO($dsn,"aaaaaa","aaaa"); } catch (PDOException $e) { echo $e->getMessage(); }
//query失敗時可以利用errorCode()和errorInfo()來做例外處理,如果query沒有出錯,errorCode()會是00000 try{ $sql = "SELECT * FROM aaa"; $sth = $db -> query($sql); if( $db -> errorCode() != '00000') { $error = $db -> errorInfo(); throw new PDOException($error[0]. " " .$error[1]. " " .$error[2]); } }catch(PDOException $e){ print_r($e -> getMessage()); }