views:

570

answers:

3

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.

+5  A: 

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

Ólafur Waage
+4  A: 

Try looking at the return value of execute, which is TRUE on success, and FALSE on failure.

Dominic Rodger
+1  A: 

You should check whether the statement executed successfully as others have said. You can also use PDOStatement::rowCount() to get the number of rows affected by a query:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

http://www.php.net/manual/en/pdostatement.rowcount.php

Tom Haigh