Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With PDO, how can I make sure that an UPDATE statement was successful?

Tags:

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

like image 606
alexx0186 Avatar asked Aug 05 '12 23:08

alexx0186


People also ask

How check PDO query is successful in PHP?

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.

How does PDO prepared statements work?

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.

Which PDO method is used to prepare a statement for execution?

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.

How can we check insert is successful in SQL PHP?

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.


1 Answers

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.

like image 192
FtDRbwLXw6 Avatar answered Dec 07 '22 23:12

FtDRbwLXw6