PDO Insert Should Throw Exception, But Doesn't
2 points.
First is pointed by @Funk Forty Niner. By default PDO send warning, not exception. You must set the error mode :
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
Second: use the "named parameters" not the "columns name" for the array in your execute method
$statement->execute([
':requestor' => $requestor_id,
':location' => $request_location
]);
Which PDO methods throw exceptions?
First of all, you can set how errors are dealt with by PDO, using the PDO::setAttribute
method, to set the PDO::ATTR_ERRMODE
(error reporting) option.
In particular, it is possible to configure PDO so it throws exceptions when there's an error, instead of reporting an "error" -- that's what I generally do.
Then, when a method can throw an exception, it should be indicated in it's documentation -- generaly, it's in the "Return value" section.
For instance, PDO::prepare
can throw an exception -- depending on error reporting (see what I wrote just before) :
If the database server cannot
successfully prepare the statement,
PDO::prepare()
returnsFALSE
or
emitsPDOException
(depending on
error handling).
As a sidenote : if you find a function / method that throws an exception, and it's not indicated in its documentation, it might be a good idea to create a bug report (see http://bugs.php.net/ ), so that problem is corrected ;-)
(Errors / mistakes / missing informations in the documentation are treated via the bug-tracker, like any other bug)
Does PDO fetch() throw an exception on failure?
The user here claims that fetch() threw an exception. I'd be very careful in assuming that it doesn't or won't throw an exception just because they are typically thrown when you prepare or bind. This is a very good reason to put the call inside a try block. So to answer the question, in the highly unlikely event of failure, yes fetch() should throw an exception and in that one case it did. Now it will be interesting to see if there are other cases as well.
PDO not throwing exception on wrong SQL query
It's probably failing because the query never gets executed and is awaiting further instructions.
Since it figures that nothing fires, then it's all valid in the eye of PDO; that is my analogy on this.
Execute it and you will see it will throw an exception.
Either by executing it after the prepare, or a simple ->query()
rather than ->prepare()
.
Is there a way to throw exceptions when any statement fails in PDO::exec()?
As mentioned in bug #61613, it is possible to get an exception if any of the statements fails.
The solution is to use emulated prepares (on by default), and PDOStatement::nextRowset():
$pdo = new PDO(...);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// on by default, not necessary unless you need to override a previous configuration
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
try {
$statement = $pdo->query('DELETE FROM unknown_a; DELETE FROM unknown_b;');
// loop through all the statements
while ($statement->nextRowset());
} catch (PDOException $e) {
echo $e->getMessage(), PHP_EOL;
}
If the first statement fails, query()
will throw an exception.
If the first statement succeeds and the second statement fails, query()
will work fine, and nextRowset()
will throw an exception.
Caveat: no further statements are executed after a failed statement. Say you have a SQL string containing 4 statements, and the third one fails:
- 1st statement:
query()
will succeed - 2nd statement:
nextRowset()
will succeed and returntrue
- 3rd statement:
nextRowset()
will fail with an exception - 4th statement:
nextRowset()
would returnfalse
; the statement is not executed.
If you're using the code above, it stops on first exception anyway.
How to handle PDO exceptions
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
PDO Exception Questions - How to Catch Them
You should look at the documentation. But If you dont find anything, you can add another catch :
<?php
try {
$stmt = $db->prepare("INSERT INTO tbl_user (id, name, password, question, answer) VALUES (NULL, :name, :password, :question, :answer)");
$stmt->bindValue(":name", $_POST['name']);
$stmt->bindValue(":password", $_POST['password']);
$stmt->bindValue(":question", $_POST['question']);
$stmt->bindValue(":answer", $_POST['answer']);
$stmt->execute();
echo "Successfully added the new user " . $_POST['name'];
} catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br>".$e->getMessage();
} catch (Exception $e) {
echo "General Error: The user could not be added.<br>".$e->getMessage();
}
?>
This must work because all exceptions of PHP plugins herits from the Exception native PHP class. (Since 5.0 if my memory is well).
Related Topics
A Problem Occurred Somewhere in the Ssl/Tls Handshake
Remove All Elements from Array That Do Not Start With a Certain String
How Safe Are Pdo Prepared Statements
Any Way to Return PHP 'Json_Encode' With Encode Utf-8 and Not Unicode
MySQL - Ignore Insert Error: Duplicate Entry
How to Find Day of Week in PHP in a Specific Timezone
Insert - Number of Bind Variables Doesn't Match Number of Fields in Prepared Statement
Laravel Certificate Verification Errors When Sending Tls Email
Sanitizing Strings to Make Them Url and Filename Safe
Upgrading PHP in Xampp For Windows
How to Create Virtual Host on Xampp
PHPmailer - Ssl3_Get_Server_Certificate:Certificate Verify Failed
Merging Arrays With the Same Keys
How to Access Dynamic Variable Names in Twig