Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO mysql: How to know if insert was successful

I'm using PDO to insert a record (mysql and php)

$stmt->bindParam(':field1', $field1, PDO::PARAM_STR); $stmt->bindParam(':field2', $field2, PDO::PARAM_STR); $stmt->execute(); 

Is there a way to know if it inserted successfully, for example if the record was not inserted because it was a duplicate?

Edit: of course I can look at the database, but I mean programmatic feedback.

like image 938
Chris Avatar asked Nov 02 '09 15:11

Chris


People also ask

How do I know if a SQL insert was successful?

You can check the @@ROWCOUNT right after insert. If it's more than 0, then the insert succeeded. Also, if @@ERROR = 0 after insert, it was successful. No, check it in T-SQL although if the insert will result in error, most likely the error will be propagated into the client.

How do you check data is inserted or not in MySQL?

Then how to test? While the mysqli_num_rows() function will return the number of rows generated by a SELECT query, mysqli_affected_rows() returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It's used like so: $num = mysqli_affected_rows($dbc);

How check PDO query is successful in PHP?

de.php.net/manual/en/pdostatement.execute.php says: Returns TRUE on success or FALSE on failure. - So bind it to a variable, e.g. $success = $STH->execute($params); and check that variable against true or false .

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).


2 Answers

PDOStatement->execute() returns true on success. There is also PDOStatement->errorCode() which you can check for errors.

like image 158
Ólafur Waage Avatar answered Sep 25 '22 12:09

Ólafur Waage


Given that most recommended error mode for PDO is ERRMODE_EXCEPTION, no direct execute() result verification will ever work. As the code execution won't even reach the condition offered in other answers.

So, there are three possible scenarios to handle the query execution result in PDO:

  1. To tell the success, no verification is needed. Just keep with your program flow.
  2. To handle the unexpected error, keep with the same - no immediate handling code is needed. An exception will be thrown in case of a database error, and it will bubble up to the site-wide error handler that eventually will result in a common 500 error page.
  3. To handle the expected error, like a duplicate primary key, and if you have a certain scenario to handle this particular error, then use a try..catch operator.

For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.

So, in a nutshell: in a regular code you don't need any error handling at all. Just keep your code as is:

$stmt->bindParam(':field1', $field1, PDO::PARAM_STR); $stmt->bindParam(':field2', $field2, PDO::PARAM_STR); $stmt->execute(); echo "Success!"; // whatever 

On success it will tell you so, on error it will show you the regular error page that your application is showing for such an occasion.

Only in case you have a handling scenario other than just reporting the error, put your insert statement in a try..catch operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the exception, to make it possible to be handled by the site-wide error handler usual way. Below is the example 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) {         // Take some action if there is a key constraint violation, i.e. duplicate name     } else {         throw $e;     } } echo "Success!"; 

In the code above we are checking for the particular error to take some action and re-throwing the exception for the any other error (no such table for example) which will be reported to a programmer.

While again - just to tell a user something like "Your insert was successful" no condition is ever needed.

like image 38
Your Common Sense Avatar answered Sep 24 '22 12:09

Your Common Sense