mysql_affected_rows() 始终返回 1,即使没有更新任何行

发布于 2024-09-01 20:03:11 字数 537 浏览 2 评论 0原文

我想做的是:(以编程方式)

更新 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉栀 2024-09-08 20:03:11

这是因为如果您使用 echotrue 将打印为“1”。对于调试,请尝试使用 var_dump(),或者让您的函数返回 0(在我看来,在这种情况下,这是更好的选择)。

一张小纸条;我认为您应该尝试使代码更具可读性(如果问题中的代码与文件中的代码具有相同的布局)。尝试缩进代码块,使用单独的行来关闭大括号,等等......

That is because true will print out as "1" if you use echo. For debugging try using var_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...

花间憩 2024-09-08 20:03:11

这只是一个猜测......

也许你的函数工作正常?也许这段代码 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 returns true 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文