It seems that for an INSERT statement, one can use if (isset($connect->lastInsertId()))
in order to check whether the INSERT statement was successful. (Please correct me if I'm wrong.)
But for an UPDATE statement, how can I know if it was successful?
For example, I have basic one like that:
$statement=$connect->prepare("UPDATE users SET premium='1' WHERE userid=?"); $statement->execute(array($id));
Thanks a lot in advance. Regards
To determine if the PDO::exec method failed (returned FALSE or 0), use the === operator to strictly test the returned value against FALSE. To execute an SQL statement that returns one or more result sets, call the PDO::query method on the PDO connection object, passing in a string that contains the SQL statement.
In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.
Description ¶ Prepares an SQL statement to be executed by the PDOStatement::execute() method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
To check if your INSERT was successful, you can use mysqli_affected_rows() . Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. And check for errors against your query and for PHP.
It depends on what you mean by "successful." If you mean that the query executed without failing, then PDO
will either throw an exception on failure or return FALSE
from PDOStatement::execute()
, depending on what error mode you have set, so a "successful" query in that case would just be one in which the execute method did not return FALSE
or throw an exception.
If you mean "successful" in that there were actually rows updated (versus just 0 rows updated), then you'd need to check that using PDOStatement::rowCount()
, which will tell you the number of affected rows from the previous query.
Warning: For updates where newvalue = oldvalue
PDOStatement::rowCount()
returns zero. You can use
$p = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
in order to disable this unexpected behaviour.
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