Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO/MySQL rowCount not returning as expected

Post-answer edit: I think this was a bug in my own code -- I don't know what it was but I proceeded to fix it. See answer below.

I'm using MySQL/PHP to perform a series of INSERT ... ON DUPLICATE KEY UPDATE statements. The documentation I've read indicates that the row count for this will return:

-1 : an error
0 : update, no changes to row made (i.e. all values duplicated)
1 : row inserted
2 : update performed on row with duplicate key

However, I'm only seeing results of 0s where I should be seeing 2s (since I am watching the code update various database values.) Here is the code:

$stmt = $db->prepare('INSERT INTO sometable (`id`, `name`, `email`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `name` = ?, `email` = ? ;');

$stmt->execute( array ( $id, $name, $email, $name, $email ) );

$rc = $stmt->rowCount();
echo $rc;

$rc is always coming up 0 for updates (even when values were definitely changed) or 1 (for successful inserts, as expected.)

What am I missing? :)

like image 675
Christian Sieber Avatar asked Aug 29 '12 02:08

Christian Sieber


1 Answers

Try using the MySQL function, if it returns the right result, the problem will be PDO:rowCount()

$stmt = $db->prepare('INSERT INTO table (`id`, `name`, `email`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `name` = ?, `email` = ? ;');

$stmt->execute( array ( $id, $name, $email, $name, $email ) );

$rc = $db->query("SELECT ROW_COUNT()")->fetchColumn();
echo $rc;
like image 84
xdazz Avatar answered Oct 19 '22 23:10

xdazz