phpmysqlcodeigniteroffsetquery-builder

CodeIgniter query with OFFSET of 1 returns one fewer rows in result set than expected


I am getting one row less than expected with my CodeIgniter code below.

When I run a query with the same WHERE logic directly in my database, I get 6 rows, but in my CodeIgniter app I only get 5 rows.

What could be the reason behind this difference?

public function get_all_book_list_ByCreatedDateDSC($limit, $start, $sortsesval)
{
    $id = 0; 
    $this->load->helper('date'); 
    $datestring = "%Y-%m-%d: %d:%h:%i";
    $time = time(); 
    $today = mdate($datestring, $time); 
    $pasttime=date("Y-m-d H:i:s", strtotime("-7 days"));
    printf('$today=' . $today);
    printf('$pasttime=' . $pasttime);

    $this->load->database();  
    $this->db->limit($limit, $start);
    $this->db->select('*'); 
    $query =$this->db
        ->join('coverdetails', 'coverdetails.cover_id = bookdetails.cover_id')
        ->where('quantity >', $id)
        ->where("bookdetails.created_date BETWEEN '$pasttime' AND '$today'")
        ->get('bookdetails');
    print_r('no of rows=' . $query->num_rows()); //output: no of rows=5

    if ($query->num_rows() > 0) {
        foreach ($query->result() as $row) {
            $data[] = $row;
        }
        return $data;
    }
    return false;
}

Solution

  • Change you function code like this

    public function get_all_book_list_ByCreatedDateDSC($limit, $start,$sortsesval)
    {
        $this->load->helper('date'); 
        $this->load->database();  
    
        $id         =   0; 
        $datestring =   "%Y-%m-%d: %d:%h:%i";
        $time       =   time(); 
        $today      =   mdate($datestring, $time); 
        $pasttime   =   date("Y-m-d H:i:s", strtotime("-7 days"));
    
    
    
        return $this->db
                    ->select('*'); 
                    ->join('coverdetails', 'coverdetails.cover_id = bookdetails.cover_id')
                    ->where('quantity >', $id)
                    ->where("bookdetails.created_date BETWEEN '$pasttime' AND '$today'")
                    ->limit($limit, $start)
                    ->get('bookdetails');
                    ->result_array();
    }
    

    Also for testing use $this->db->last_query() and copy the query than paste it in PHP MyAdmin to test. Other possibilities are $limit and $offset and Between that may cause the change in number of records.