function sql_add($name,$db_handle) { try{ $statement = $db_handle->prepare ( 'INSERT INTO qiangpiao(name,xuehao,xiaoqu,zuoweihao,time) VALUES (:name,:xuehao,:xiaoqu,:zuoweihao,:time)' ); $number = $db_handle->prepare ( 'select count(1) from qiangpiao' ); $number->execute(); /*變數的定義*/ $matches = array(); $matches = fenci($name); $name = $matches[1]; $xuehao = $matches[2]; $xiaoqu = $matches[3]; $zuoweihao = $number->fetch();//通過資料庫來增加資料 echo $zuoweihao[0]; echo "\n"; $time = date("Y-m-d H:i:s",time()); echo $time; /*資料繫結*/ $statement->bindParam(':name',$name); $statement->bindParam(':xuehao',$xuehao); $statement->bindParam(':xiaoqu',$xiaoqu); $statement->bindParam(':zuoweihao',$zuoweihao[0]); $statement->bindParam(':time',$time); $statement->execute(); return; }catch(PODException $e){ echo $e->getMessage(); } }
在資料庫中,我設定了主鍵為學號,重複的話應該會返回一個異常,但我沒有捕獲到異常,是什麼原因,有沒有什麼解決方案。
回複內容:
function sql_add($name,$db_handle) { try{ $statement = $db_handle->prepare ( 'INSERT INTO qiangpiao(name,xuehao,xiaoqu,zuoweihao,time) VALUES (:name,:xuehao,:xiaoqu,:zuoweihao,:time)' ); $number = $db_handle->prepare ( 'select count(1) from qiangpiao' ); $number->execute(); /*變數的定義*/ $matches = array(); $matches = fenci($name); $name = $matches[1]; $xuehao = $matches[2]; $xiaoqu = $matches[3]; $zuoweihao = $number->fetch();//通過資料庫來增加資料 echo $zuoweihao[0]; echo "\n"; $time = date("Y-m-d H:i:s",time()); echo $time; /*資料繫結*/ $statement->bindParam(':name',$name); $statement->bindParam(':xuehao',$xuehao); $statement->bindParam(':xiaoqu',$xiaoqu); $statement->bindParam(':zuoweihao',$zuoweihao[0]); $statement->bindParam(':time',$time); $statement->execute(); return; }catch(PODException $e){ echo $e->getMessage(); } }
在資料庫中,我設定了主鍵為學號,重複的話應該會返回一個異常,但我沒有捕獲到異常,是什麼原因,有沒有什麼解決方案。
PODException
好像只會在new POD
的時候拋出,其他時候都得判斷execute()
的傳回值來確定操作是否成功,並通過errorCode()
,errorInfo()
來擷取錯誤的資訊……
預設不把錯誤當異常拋出,你需要使用 errorCode() 來判斷是否執行成功。
你可以設定
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
這樣來使得 SQL 執行出錯的時候拋出異常。