用于 UPDATE 的 mysqli_affected_rows 有时在全行匹配时返回 0 [英] mysqli_affected_rows for UPDATE sometimes returns 0 on full row match

查看:37
本文介绍了用于 UPDATE 的 mysqli_affected_rows 有时在全行匹配时返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说,如果我有 MySQL 查询来更新一行:

Say, if I have MySQL query to update a row:

$res = mysqli_query($link, 
    "UPDATE table SET val=1 WHERE id=5");

if($res)
{
    if(mysqli_affected_rows($link) > 0)
    {
        echo("Updated something!");
    }
    else
        echo("Didn't update");
}
else
    echo("Error");

如何更改它以区分这 3 个条件:

How do I change it to distinguish between these 3 conditions:

  1. 找到带有 id=5 的项目并设置它.
  2. 未找到 id=5 的项目.
  3. 错误
  1. Found item with id=5 and set it.
  2. Did not find item with id=5.
  3. Error

按照现在的编写方式,如果我的数据库列 val 在该行中已经有 1mysqli_affected_rows 将返回 0.

In the way it's written now, if my database column val already has 1 in that row, mysqli_affected_rows will return 0.

推荐答案

您可以使用 mysqli_info 来获取你需要区分这两种情况的信息.mysqli_info($link)UPDATE 查询之后将返回一个类似

You can use mysqli_info to get the information you need to distinguish between the two cases. mysqli_info($link) after an UPDATE query will return a string something like

Rows matched: 1 Changed: 1 Warnings: 0

然后你可以解析,例如使用 preg_match:

which you can then parse, for example using preg_match:

// $info = mysqli_info($link);
$info = 'Rows matched: 12 Changed: 8 Warnings: 0';
preg_match('/Rows matched: (\d+) Changed: (\d+)/', $info, $matches);
list(, $matched, $changed) = $matches;
echo "$matched rows matched, $changed rows changed\n";

输出:

12 rows matched, 8 rows changed

然后您可以使用 $matched$changed 中的值来区分您的两种情况.

You can then use the values in $matched and $changed to distinguish between your two cases.

这篇关于用于 UPDATE 的 mysqli_affected_rows 有时在全行匹配时返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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