How to confirm the UPDATE with PDO

2

Do you have a function in the PDO that allows you to check if the UPDATE was successful? Same as method 'lestInsertId ()' is used to check if a new ID was generated in a table with auto increment after an INSERT.

    
asked by anonymous 13.01.2017 / 01:20

1 answer

2

You can use 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 rows affected.

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 query worked or not because of errors. For errors, you have the traditional methods.

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

Manual:

  

link


If you are using MySQL , you have an option to initialize the PDO that changes the behavior of the return so that rowCount returns values even if UPDATE found the rows but did not change by value to be equal:

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

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

    
13.01.2017 / 01:24