mysql_affected_rows() 始终返回 1,即使没有更新任何行
我想做的是:(以编程方式)
更新 id 为某事的状态,如果没有更新行,则给出错误:我们找不到 id 为某事的记录,否则给出消息成功。
在这里,我使用 mysql_affected_rows() 来了解一行是否已更新,但它总是返回 1,因此用户会收到成功消息,即使没有更新行。
谁能告诉我这可能是什么?
代码如下:
function update_sql($sql) {
$this->last_query = $sql;
$r = mysql_query($sql);
if (!$r) {
$this->last_error = mysql_error();
return false;
}
$rows = mysql_affected_rows();
if ($rows == 0) return true; // no rows were updated
else return $rows; }
此代码返回 1。
What I am trying to do is: (programmatically)
Update status where id is something, if no rows where updated, give error: we cannot find the record with id something, otherwise give message success.
Here I am using mysql_affected_rows() to know if a row was updated or not, but it always return 1, so the user gets a success message, even though there was no row updated.
Can anyone tell me what could it be?
Here's the code:
function update_sql($sql) {
$this->last_query = $sql;
$r = mysql_query($sql);
if (!$r) {
$this->last_error = mysql_error();
return false;
}
$rows = mysql_affected_rows();
if ($rows == 0) return true; // no rows were updated
else return $rows; }
This code returns 1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为如果您使用
echo
,true
将打印为“1”。对于调试,请尝试使用var_dump()
,或者让您的函数返回 0(在我看来,在这种情况下,这是更好的选择)。一张小纸条;我认为您应该尝试使代码更具可读性(如果问题中的代码与文件中的代码具有相同的布局)。尝试缩进代码块,使用单独的行来关闭大括号,等等......
That is because
true
will print out as "1" if you useecho
. For debugging try usingvar_dump()
, or let your function return 0 (which seems to me, in this case, the better option).One little note; I think you should try to make your code a bit more readable (if the code in your question has the same layout as the code in your file). Try to indent code blocks, use separate lines for closing curly brackets, etc...
这只是一个猜测......
也许你的函数工作正常?也许这段代码
if ($rows == 0) return true;
工作正常,并返回true
但你将该值视为整数(布尔 true 可以显示为1)?执行:var_dump(uddated_sql('YOUR QUERY'))
并检查它是否返回布尔 true 或整数 1 值。This is just a guess...
Maybe your function works as excepted? Maybe this piece of code
if ($rows == 0) return true;
works fine, and returnstrue
but you treat that value as integer (boolean true can be displayed as 1)? Do:var_dump(uddated_sql('YOUR QUERY'))
and check whether it returns boolean true or integer 1 value.