RDowns
RDowns

Reputation: 659

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 Loss identified in the table as L.

    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)){

           if(!empty($row)){

                $returnValue = mysqli_num_rows($result);
           }
        }

       return $returnValue;

  }

}

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

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

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

Upvotes: 0

Views: 50

Answers (1)

icoder
icoder

Reputation: 165

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

Upvotes: 1

Related Questions