dousi5358 2013-03-20 14:25
浏览 60
已采纳

PHP mysql_affected_rows()我应该关心吗?

I have always struggled with a fairly basic concept in my PHP INSERT/UPDATE code. Should I always be checking for the number of affected rows after every INSERT/UPDATE because in the vast majority of times I am only ever performing one INSERT/UPDATE and it seems to cause more problems than it fixes by checking that only one row was affected.

Below is my standard code to perform the INSERT/UPDATE and this code fails if the user is updating a record without changing anything because the affected rows will be 0. I could write code to check that at least one field has changed but on large forms this seems very clunky and was wondering if it is really worth it because I have never really ever caught any errors by checking this number anyway.

<?php
        $whereSql = '';
        $groupSql = 'INSERT INTO';

        if(isset($_POST['id']) && is_numeric($_POST['id'])){
            $groupSql = 'UPDATE';
            $whereSql = 'WHERE id = ' . $_POST['id'];
        }

        $groupSql .= ' sometable SET name="' . $name . '" ' . $whereSql;

        $groupDb = mysqli_query($groupSql, $dbObject) or die("Login DB error:".mysql_error());

        if(mysqli_affected_rows($dbObject) == 1){
            //redirect
        }else{
            die('System Error');
        }  
  • 写回答

2条回答 默认 最新

  • dongtiao0279 2013-03-20 14:31
    关注

    You should be checking return values on queries. A select/update query which affects/returns no rows is NOT an error condition, it's simply an empty result set, or an update which happened to affect nothing.

    $result = mysql_query($sql) or die(mysql_error());
                                ^^^^^^^^^^^^^^^^^^^^^
    

    Consider a user signup system which checks for the existence of a matching username:

    SELECT id FROM users WHERE username='foo';
    

    if the user foo does not exist, your system will barf and claim an error occurred. But an empty result set is NOT an error. It simply means the username is available for user.

    Same for a system that handles grades:

    UPDATE students SET failed=true WHERE score < 50;
    

    getting 0 affected rows is NOT a failure. It just means all the students passed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序