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 let's say a duplicate IDNumber, I want this displayed to the user.
If I simply try to echo the variable $exception it does not work.
I want to return the MySQL error to the user.
You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION. And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.
Sometimes errors happen when you attempt to connect to a database or issue an SQL statement. The password for your connection might be incorrect, a table you referred to in a SELECT statement might not exist, or the SQL statement might be invalid.
The main advantage of PDO over MySQLi is in the database support. PDO supports 12 different database types, in opposition to MySQLi, which supports MySQL only. When you have to switch your project to use another database, PDO makes the process simpler.
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
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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With