gandrap
gandrap

Reputation: 139

How can I get the number of rows affected after executing an update query?

The following is the code:

$count = 0;
$update = $db->query("UPDATE $table SET price = '$price' WHERE sku = '$sku'");
        if ($update->affected_rows) {
        $count++;
        }   
echo $count;

After executing the above code, rows are getting updated in the db, but value of $count is 0. As per my assumption, the value of $count should be 122, just because 122 rows are updated. I'm not getting why.

When I use the below code,

if (!$update->affected_rows) {
            $count++;
            }   

the $count becomes 212.

I'm not able to understand the behaviour. I would want someone to explain the above code and how it behaves?

Upvotes: 1

Views: 142

Answers (2)

Ajit Kumar
Ajit Kumar

Reputation: 345

$db->query return the object result try this : $affected_rows = $db->exec("UPDATE table SET field='value'"); echo $affected_rows.' were affected' for more http://php.net/manual/en/pdo.exec.php

Upvotes: 0

user247217
user247217

Reputation: 394

Try below code.

$update = $db->query("UPDATE $table SET price = '$price' WHERE sku = '$sku'");
        if ($update) {
       printf("Records Updated: %d\n", mysql_affected_rows());
        }   

Hope this helps.

Upvotes: 5

Related Questions