Pregunta

I use this piece of php to insert/update mysql db. Please see my question in the comment part at corresponding lines. Thanks.

        //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));
        }

I also tried these, but both num_rows and affected_rows return 0. why?

       $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);

Thanks for your help!

¿Fue útil?

Solución

If UPDATE doesn't match anything to update it will simply return. This is not an error. To find out whether it's updated anything use mysql_affected_rows().

Note: mysql_*() doesn't support the OOP form, so you should use mysql_affected_rows(), which should work for your second case above.

This will give you:

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';
       }

Side note: mysql_*() is deprecated and will be removed. You should use mysqli or PDO for new code.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top