Dr. Atul Tiwari
Dr. Atul Tiwari

Reputation: 1085

How to return in PHP, if row was updated using mysql query

I am using following query/piece of code, for updating a MySQL database via PHP -

$sql = "UPDATE test_table SET lastname='ram' where id=1";
$result = mysql_query($sql); 
echo $result;

the problem with this is, the PHP output is 1 even if there was no updating done. for e.g. in my case, there is no row that contains id=1 so when I run this query in phpmyadmin it says 0 rows affected, while the using the same query in PHP is returning 1.

My question is - how to know, if the update was done ($result = 1) or not ($result = 0) without using a new select query to check the change?

Upvotes: 1

Views: 126

Answers (1)

Mureinik
Mureinik

Reputation: 311308

mysql_query returns true when an update succeeds (i.e., runs without an error, regardless of how many rows it did or did not update). If you want the number of rows you've actually updated, you need to call mysql_affected_rows:

$sql = "UPDATE test_table SET lastname='ram' where id=1";
if (mysql_query($sql)) {
    $result = mysql_affected_rows();
    echo $result;
}

Upvotes: 4

Related Questions