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
It depends on what you mean by “successful.” If you mean that the query executed without failing, then
PDOwill either throw an exception on failure or returnFALSEfromPDOStatement::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 returnFALSEor 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 = oldvaluePDOStatement::rowCount()returns zero. You can usein order to disable this unexpected behaviour.