How can I test to see if the following query executed successfully?
$STH = $this->_db->prepare("UPDATE UserCreds SET VerificationString=:newVerificationString, ExpiryDate=:expiryDate WHERE UserID = :userID;"); $STH->execute($params);
I know I can use lastInsertId()
when I'm adding new rows, but what about UPDATEs and SELECTs?
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.
Return Values ¶ If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns false or emits PDOException (depending on error handling).
Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all. Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.
The execute
returns true
on success and false
on failure.
From Docs:
Returns TRUE on success or FALSE on failure.
So you can make sure query ran successfully like:
if ($STH->execute($params)) { // success } else { // failure }
execute() returns true/false based on success/failure of the query:
$status = $STH->execute($params); if ($status) { echo 'It worked!'; } else { echo 'It failed!'; }
One note: a select query which returns no rows is NOT a failure. It's a perfectly valid result that just happens to have NO results.
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