-2

I got the following testing SQL statement that link to the database. I do not have any record in the database that matches 900 but it returns the results = 1 instead of 0. Can I know what is the reason for this?

$query = "update mytable set verify = 'yes' where number ='900'";

$result = $conn->query($query);

if (!$result){
    $json_out = "[" . json_encode(array("result"=>0)) . "]";        
}
else {
    $json_out = "[" . json_encode(array("result"=>1)) . "]";        
}

echo $json_out;
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
nmm
  • 117
  • 1
  • 10
  • Because you have put `json_encode(array("result"=>1))` – Sinto Jan 16 '19 at 04:16
  • No record in the database is changed despite it running the statement. I just need it to be result = 0 when it does not meet condition so that I can show error message at the front end – nmm Jan 16 '19 at 04:23
  • Ya, I know that. But the query executed fine & there will be a `$result`, you can use `print_r($result)` to see if there is any & confirm. – Sinto Jan 16 '19 at 04:25
  • @Sinto what are you expecting to see from `print_r($result))`? – mickmackusa Jan 16 '19 at 04:39
  • I was trying to say that the `$result` will be `true` even if there is no affected rows in DB as per above code. So that he can confirm that by himself by using `print_r()` or `var_dump()`. – Sinto Jan 16 '19 at 05:09

1 Answers1

2

You get the 1 result because you are not checking for affected rows. The query has no errors, so you get the 1 outcome.

For your outcome to be accurate you need to check zero versus non-zero affected rows.

http://php.net/manual/en/mysqli.affected-rows.php

Untested suggestion:

echo json_encode(['result' => (int)($conn->query("UPDATE mytable SET verify = 'yes' WHERE number = '900'") && $conn->affected_rows)]);

In other words, if the query returns a non-false result and the affected rows result is non-zero, then the whole condition evaluates as true. If you cast true as an integer, you get 1; false becomes 0.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136