phpmysqlcodeignitersummysql-num-rows

CodeIgniter query built with select_sum() incorrectly returns 1 from num_rows() when no qualifying records


Why does my script always say that a row is in the result set even if there where no qualifying records?

$this->db->select_sum('score_0')
    ->select_sum('score_1')
    ->select_sum('score_2')
          ..........
    ->select_sum('score_97')
    ->select_sum('score_98')
    ->select_sum('score_99');
$this->db->where('score_game_id',$game_id);
$this->db->order_by('score_id','asc');
$query = $this->db->get($this->tbl_lotteryApp_scores_twodigit);     
if ($query->num_rows() > 0){

}

Solution

  • I think this is the best solution for this situation:

    function sum_score($game_id){
        if($this->check_for_scores($game_id)==true)
        {
            $this->db->select_sum('score_0')
            ->select_sum('score_1')
            ->select_sum('score_2')
                  ...........
            ->select_sum('score_98')
            ->select_sum('score_99');
            $this->db->where('score_game_id',$game_id);
            $this->db->order_by('score_id','asc');
            $query = $this->db->get($this->tbl_lotteryApp_scores_twodigit);     
            return  $query->result();
        }
    
    }
    
    function check_for_scores($game_id)
    {
        $this->db->where('score_game_id',$game_id);
        $this->db->order_by('score_id','asc');
        $query = $this->db->get($this->tbl_lotteryApp_scores_twodigit);     
        if ($query->num_rows() > 0){    
            return true;
        }else{
            return false;
        }
    }
    

    This worked for me :)