Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL no affected rows upon UPDATE when value not changed

MySQL with PHP, trying to update a row:

$dbQuery = 'UPDATE UserTable SET Age=25 WHERE Id=3';
$result = mysqli_query($dbLink, $dbQuery);
if ($result === FALSE) {
  // Take care of error
}
else {
  $numAffectedRows = mysqli_affected_rows($dbLink);
}

I get zero $numAffectedRows in two different cases:
1. When there is no user row with Id=3
2. When there is a user row with Id=3 but Age was already 25 before

Is there a way I can distinguish between the two cases? (apart from reading the row before and manually check the value before updating)

like image 791
Free Bud Avatar asked Aug 25 '14 08:08

Free Bud


People also ask

How check row is affected in MySQL?

mysql_affected_rows() may be called immediately after executing a statement with mysql_real_query() or mysql_query() . It returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE , DELETE , or INSERT . For SELECT statements, mysql_affected_rows() works like mysql_num_rows() .

What happens if you update a record that doesn't exist SQL?

Update won't insert records if they don't exist, it will only update existing records in the table. Save this answer.

Does limit work on update MySQL?

Yes, it is possible to use UPDATE query with LIMIT in MySQL.


1 Answers

According to mysql documentation, you can change the behaviour of affected_rows by passing the MYSQLI_CLIENT_FOUND_ROWS flags while connecting using mysql_real_connect.

In this case, mysql_affected_rows returns the number of rows matched by the WHERE condition, not the number of updated rows.

like image 119
GHugo Avatar answered Nov 08 '22 09:11

GHugo