tags:

views:

164

answers:

1

I am trying to write a PHP-MySQL database processor that is somewhat intelligent. When this processor decides it needs to make an update, I want to report if it was really successful or not. I thought I could use mysql_affected_rows...

// Example:
// After running query "UPDATE mytable SET name='Test' WHERE ID=1"
$result = mysql_affected_rows();
if ($result >= 1) { /* Success */ }

If, for example, there was no row with ID=1, then $result would be 0.

However, it turns out that PHP's mysql_affected_rows is the actual affected rows, and may be still be 0 if the row exists but name was already "Test". (The PHP docs even say this is the case).

If I run this in the command line, I get the following meta information about the query:

Query OK, 0 rows affected (0.01 sec)
Rows matched: 1  Changed: 0  Warnings: 0

Is there any way for me to get that "Rows matched" value in PHP instead of the affected rows?

[Edit]: I should note that I know I can run a separate query, but I'd like to not do that, for the sake of performance.

+2  A: 

From the MySQL documentation for mysql_affected_rows:

For UPDATE statements, if you specify the CLIENT_FOUND_ROWS flag when connecting to mysqld, mysql_affected_rows() returns the number of rows matched by the WHERE clause. Otherwise, the default behavior is to return the number of rows actually changed.

In PHP, you can specify the CLIENT_FOUND_ROWS passing the value 2 as the 5th parameter for mysql_connect:

http://www.php.net/manual/en/function.mysql-connect.php

PS: I'm not sure if all versions of PHP will accept this flag. I tested with 5.2.12 and it worked as expected. You can see other flags in the first comment of this page.

Vinicius Pinto
This is great. While it doesn't offer me a way to distinguish between the two (so I'm going to test it before accepting the answer) it seems to me to be the preferable condition in my case. Thanks!
Renesis
i like his answer better than mine! :)
Sev