PHP MySQL 更新不存在的记录


php mysql update non-existent record

我用这段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);

感谢您的帮助!

如果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用于新代码。

相关文章: