PDO/MySQL rowCount未按预期返回 [英] PDO/MySQL rowCount not returning as expected

查看:105
本文介绍了PDO/MySQL rowCount未按预期返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

答案后我认为这是我自己的代码中的错误-我不知道它是什么,但是我着手对其进行了修复.请参阅下面的答案.

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.

我正在使用MySQL/PHP执行一系列INSERT ... ON DUPLICATE KEY UPDATE语句.我已阅读的文档指出,此操作的行数将返回:

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

但是,我只看到0s的结果,而应该看到2s(因为我正在看代码更新各种数据库值.)这是代码:

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总是为0,对于预期的成功插入,总是为1.

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

我想念什么? :)

推荐答案

尝试使用MySQL函数,如果返回正确的结果,则问题将出在PDO:rowCount()

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;

这篇关于PDO/MySQL rowCount未按预期返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆