区分“不影响任何行"和成功更新的行

编程入门 行业动态 更新时间:2024-10-20 03:56:41
本文介绍了区分“不影响任何行"和成功更新的行-值相同(MySQL和PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从PHP执行SQL(MySQL)命令.每次执行都有几种可能的结果:

I am executing SQL (MySQL) commands from PHP. There are several possible outcomes to each execution:

  • 记录已更新为新值
  • 记录已更新,但值恰好相同
  • 记录找不到要更新的行(即,没有与WHERE子句匹配的行)
  • Record updated to new value
  • Record updated, but values happen to be the same
  • Record finds no rows to update (ie, no rows match the WHERE clause)
  • 我想知道如何区分#的1和3:这两种情况都会随着受影响的行数返回零,所以:

    I am wondering how to differentiate between #'s 1 and 3: both cases return zero as the number of rows being affected, so:

    $result = $db->exec($statement)

    在两种情况下,

    将具有$result == 0.我该如何区分?

    will have $result == 0 in both cases. How can I tell the difference?

    编辑:我的意思是要问如何区分场景2和3,而不是1和3!抱歉给您带来不便...

    I meant to ask how to differentiate between scenarios TWO and 3, not 1 and 3! Sorry for the inconvenience...

    推荐答案

    一个简单的解决方案是两个查询.

    A simple solution would be two queries.

    首先,使用mysqli_num_rows()运行SELECT查询以检查该行是否存在.

    First, run a SELECT query to check if the row exists using mysqli_num_rows().

    然后,如果该行存在,则可以运行UPDATE查询并使用mysqli_affected_rows().

    Then, if the row exists, you can run the UPDATE query and use mysqli_affected_rows().

    ...对于任何寻求一个电话的人,我都会建议一个潜在的替代方法.我不知道您是否有兴趣进行任何INSERT或纯粹的UPDATE.以下是一些值得深思的地方:

    ...I'll suggest a potential alternative for anyone seeking out a single call. I don't know if you are interested in doing any INSERTs, or purely UPDATEs. Below is some food for thought:

    在顶部评论中@ php/manual/en/mysqli.affected-rows.php :

    在在重复键更新中插入到查询中"查询中,尽管成功的查询可能希望受影响的行每行仅返回0或1,但实际上可能返回2.

    On "INSERT INTO ON DUPLICATE KEY UPDATE" queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

    从Mysql手册中:使用ON DUPLICATE KEY UPDATE,如果将行作为新行插入,则每行的受影响行值为1;如果更新现有行,则受影响的行值为2."

    From Mysql manual: "With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."

    请参阅: dev.mysql. com/doc/refman/5.0/en/insert-on-duplicate.html

    这是每行的总细目:

    +0:未更新或插入行(可能是因为该行已存在,但在UPDATE期间实际上未更改任何字段值)

    +0: a row wasn't updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)

    +1:已插入一行

    +2:行已更新

    您能满足自己的需求吗?

    Can you make that suit your needs?

    更多推荐

    区分“不影响任何行"和成功更新的行

    本文发布于:2023-10-26 23:40:51,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1531682.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:quot

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!