PDO - check if a row is updated?

Other people asked this question, but mine is a bit more specific.

I have this query:

$sql = "UPDATE table SET option=? WHERE number=?"; $q = $conn->prepare($sql); $q->execute(array($option, $number)); $q->setFetchMode(PDO::FETCH_BOTH); echo $q->rowCount(); 

If a WHERE number already exists and the SET option the same, $q->rowCount() is 0

If the WHERE number does not exist and the row is not updated, $q->rowCount() is 0

How can I distinguish between these non-updates?

+3
source share
3 answers

In recent versions of PHP, it is controlled by the PDO::MYSQL_ATTR_FOUND_ROWS . If set to true , according to the doc effect:

 Return the number of found (matched) rows, not the number of changed rows. 
+8
source

You can try using REPLACE , which works like an insert, but if the row already exists, it was first deleted and then inserted. This is due to mysql overload

0
source

Would it be better to check if exists? I use a generic function for this in my mini-class to manage PDO, but I don’t know if this is the best solution, because to make one request more ...

 function checkExistsInDatabase($id, $table, $where = null){ // Connect $Database = Database::connect(); // Query $sql = "SELECT id FROM $table WHERE id = :id $where LIMIT 1"; $params = array( ':id' => array( 'value' => $id, 'type' => 'int' ) ); $q = $Database->query($sql, $params); // Ha encontrado algo? $resultados = $Database->fetchArray($q); if(count($resultados) === 1){ return true; }else{ return false; } } 
0
source

Source: https://habr.com/ru/post/948839/


All Articles