問(wèn)題描述
我有一個(gè)使用 PDO 執(zhí)行的插入語(yǔ)句.插入效果很好,但是如果出現(xiàn)錯(cuò)誤,我希望將其顯示給用戶.
I have an insert statement that is executed with PDO. Insert works great however if there is an error I would like it displayed to the user.
我有以下 try-catch 塊.
I have the below try-catch block.
try{
$insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
$insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));
}
catch(PDOException $exception){
return $exception;
}
如果查詢失敗,或者假設(shè)有重復(fù)的 IDNumber,我希望將其顯示給用戶.
If the query fails, or let's say a duplicate IDNumber, I want this displayed to the user.
如果我只是嘗試回顯變量 $exception 它不起作用.
If I simply try to echo the variable $exception it does not work.
我想將 MySQL 錯(cuò)誤返回給用戶.
I want to return the MySQL error to the user.
推薦答案
默認(rèn)情況下 PDO 不處于會(huì)顯示錯(cuò)誤的狀態(tài).您需要在數(shù)據(jù)庫(kù)連接中提供以下內(nèi)容
By default PDO is not in a state that will display errors. you need to provide the following in your DB connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
更多信息見這里
這篇關(guān)于pdo 捕獲并輸出 mysql 錯(cuò)誤的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!