php mysql更新不存在的记录

时间:2013-11-10 18:47:54

标签: php sql insert-update

我使用这段php来插入/更新mysql db。请在相应行的评论部分查看我的问题。感谢。

        //Connecting to your database
        mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
        mysql_select_db($dbname);

        arr = array();
        if (strcasecmp($actionIn, 'insert') == 0) {
           $query = "INSERT INTO $usertable (id, fname, lname) VALUES ('$id', '$fname', 'lname'";
           $result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, I would get error message if I insert a duplicated id into table, no following json_encode would not print out, that's what I want.
           if ($result) {
              $arr['inserted'] = 'true';
           }
           exit(json_encode($arr));
        }

        if (strcasecmp($actionIn, 'update') == 0) {
           $query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
           $result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, if I update a non-existent id, I don't get error, and the following steps continue to execute. I want the error info or return me a false.
           if ($result) {
              $arr['updated'] = 'true';
           }
       exit(json_encode($arr));
        }

我也试过这些,但num_rows和affected_rows都返回0.为什么?

       $row_cnt = $result->num_rows;
           printf("Result set has %d rows.\n", $row_cnt);
       $aff_cnt = $result->affected_rows;
       printf("Result set aff %d rows.\n", $aff_cnt);

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

如果UPDATE与要更新的任何内容不匹配,则只会返回。这不是错误。要查明是否更新了任何内容,请使用mysql_affected_rows()

注意:mysql_*()不支持OOP表单,因此您应该使用mysql_affected_rows(),这应该适用于您的第二种情况。

这会给你:

if (strcasecmp($actionIn, 'update') == 0) {
       $query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
       $result = mysql_query($query) or die(mysql_error()); 
       if (mysql_affected_rows() !== 0) {
          $arr['updated'] = 'true';
       }

附注:mysql_*()已弃用,将被删除。您应该使用mysqliPDO来获取新代码。