How to confirm the PDO UPDATE

Asked

Viewed 1,810 times

3

Do you have a PDO function that allows you to check if UPDATE successfully competed? Same as the method 'lestInsertId()' is used to verify if a new ID has been generated in an auto incremented table after an INSERT.

1 answer

3


You can use the rowCount:

$stmt->rowCount();

When you make a SELECT, it returns the amount of results, but when it does UPDATE, DELETE etc it returns the number of affected lines.

if( $stmt->rowCount() > 0 ) {
   echo 'ocorreram alterações na tabela';
} else {
   echo 'nada foi alterado';
}

Note that this has nothing to do with testing whether the query worked or not because of errors. For errors, you have the traditional methods.

The answer is basically how to confirm whether there was update or not, the other errors should always be checked anyway.

Handbook:

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


If you’re using MySQL, has an option when initializing PDO that changes the behavior of the return form to the rowCount return values even if the UPDATE located the lines, but did not change the value being equal:

$pdo = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));

Originally if Voce makes one UPDATE tabela SET valor = 0 WHERE id = 0;, and the value was already zero in the table, this is not counted as update, even if existing id equal to zero. The property PDO::MYSQL_ATTR_FOUND_ROWS serves to change behavior by returning the number located by WHERE, and not the values actually changed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.