I wonder why there is still no right answer.
Given that the most recommended error mode for PDO is ERRMODE_EXCEPTION , there is no direct execute() checking the result will never work . Since the execution of the code does not even reach the condition suggested in the other answers.
So, there are three possible scenarios for processing the result of an insert operation in a PDO:
- To report success, no verification is required. Just follow the flow of your program.
- To deal with an unexpected error, keep the same thing - no immediate processing code is required. In the event of a database error, an exception will be thrown and it will pop up to the system-wide error handler, which will ultimately lead to a 500 common error page.
- To handle the expected error, for example, a duplicated primary key, and if you have a specific script to handle this error itself , use the
try..catch .
For the average PHP user, this sounds a bit alien - how is it, and not for checking the direct result of an operation? - but here's how the exceptions work - you check for an error somewhere else. Once for everyone. Very comfortably.
So, in the normal case, you don’t need the processing code at all. Just save your code as is:
$stmt->bindParam(':field1', $field1, PDO::PARAM_STR); $stmt->bindParam(':field2', $field2, PDO::PARAM_STR); $stmt->execute(); echo "Success!";
If successful, this will tell you that if it fails, it will show you a page with regular errors that your application shows for such a case.
Only if you have a processing script , in addition to the error message, put the insert statement in the try..catch , check whether this error was expected and handle it; or - if the error was any other - throw an exception so that you can normally handle the error handler throughout the territory. The following is a sample code from my article on error handling with PDO :
try { $pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data); } catch (PDOException $e) { if ($e->getCode() == 1062) {
In the above code, we check that a specific error performs some actions and repeatedly throws an exception for any other error (for example, there is no such table) that will be reported to the programmer.
While again - just to tell the user something like "Your insert was successful" No condition is required.