pdo catch and output mysql errors

半世苍凉 提交于 2019-12-13 11:38:12

问题


Still trying to get my head around pdo.

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.

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

If the query fails, or lets say a duplicate IDNumber, I want this displayed to the user.

If I simply try echo the variable $exception it does not work.

I want to return the mysql error to the user.

Any advice appreciated as always.

Thanks, Ryan

UPDATE

new code as per proposed answers:

   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->getMessage(); 
    } 
echo "exception: ".$exception;

回答1:


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);

More info can be seen Here




回答2:


You should use this:

return $exception->getMessage();

See the page on the documentation of Exception class:

http://www.php.net/manual/en/exception.getmessage.php




回答3:


1.Add ERRMODE_EXCEPTION mode after your db connection:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

2.And than you must use try{} catch{} method for all your mysql query. Like this:

try {
    $SQL = "DELETE FROM items WHERE item_id=:item_id";
    $m = $dbh->prepare($SQL);
    $m->bindParam(':item_id', $item_id, PDO::PARAM_INT);
    $m->execute();
    //success
    $return = "Your success message.";
}
catch (PDOException $e) {
    //error
    $return = "Your fail message: " . $e->getMessage();
}


来源:https://stackoverflow.com/questions/12976697/pdo-catch-and-output-mysql-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!