4

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

谢谢你的帮助!

4

1 回答 1

6

如果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_*()已弃用并将被删除。您应该使用mysqliorPDO来获取新代码。

于 2013-11-10T18:57:32.360 回答