RDowns RDowns - 1 year ago 55
MySQL Question

How do I get this MySQL query / PHP function to return a zero if nothing is found?

The following function queries my database to see how many losses a user has had- this works great as long as the user has had at least 1

identified in the table as

public function getTotalLosses($playerId){

$returnValue = array();
$sql = "SELECT player1_result, player2_result FROM `results` WHERE player1_id = '".$playerId."' AND player1_result = 'L' OR player2_id = '".$playerId."'AND player2_result = 'L'";

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

if($result != null && (mysqli_num_rows($result) >= 1)){

while($row = $result -> fetch_array(MYSQLI_ASSOC)){


$returnValue = mysqli_num_rows($result);

return $returnValue;



How do I amend the code so if nothing is returned, a
is put into $returnValue?

I have tried
if (empty($result)) { $returnValue = 0 }
if $result == null { $returnValue = 0 ; }

But neither did anything - unless I put that bit of code in the wrong place...

Answer Source

To write correct condition you need to know what query() function returns ($this->conn->query()). As alternative variant I'd suggest to check number of selected rows:

if (mysqli_num_rows($result) === 0) {
   $returnValue = 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download