2017-04-19 106 views
0

我有工作應該是爲了獲取它的控制器準備的拼版數據這個輔助方法...... 基本上,這是發生在助手笨返回錯誤的「分頁」結果

if (!isset($_GET['page'])) { 
    $_GET['page'] = 1; 
} 
if (!isset($_GET['per_page'])) { 
    $_GET['per_page'] = 5; 
} 
$results = $ci->$model->get('', $_GET['per_page'], $_GET['page']); 

代碼這是我的模型,它應該返回數據

public function get($tableName = "", $limit = null, $start = null) 
    { 
     if ($tableName == "") { 
      $tableName = $this->table; 
     } 
     if ($limit != null && $start != null) { 
      // problem is here with limit and start which returns wrong data 
      $this->db->limit($limit, $start); 
      $query = $this->db->get($tableName); 
      var_dump($query->result()); 
      die(); 
      } 
     } else { 
      $query = $this->db->get($tableName); 
     } 
     return $query->result(); 
    } 

問題是,從模型返回的數據是不正確的,我無法弄清楚如何正確獲取基於頁碼和每頁項目數據... 。 所以在我的情況下,如果我請求數據與paramas $_GET['page'] = 1$_GET['per_page'] = 5它將返回5條記錄,但從記錄2開始,直到記錄6.所以我的問題是如何正確請求給我說5條記錄在第一頁上,然後給我另外5條記錄第2頁ETC ...

如果您需要任何其他信息,請讓我知道,我會提供。謝謝

回答

2

問題就出在你的$開始的變量。你應該記住,使用獲得的第一個5個記錄時,你應該使用一個偏移量爲0而不是1開始計數從0記得:)

的代碼應該是

public function get($tableName = "", $limit = null, $start = null) 
{ 
    if ($tableName == "") { 
     $tableName = $this->table; 
    } 
    if ($limit != null && $start != null) { 
     // problem is here with limit and start which returns wrong data 
     //$this->db->limit($limit, $start); 
     // use this instead 
     $this->db->limit($limit, ($start - 1) * $limit); 
     $query = $this->db->get($tableName); 
     var_dump($query->result()); 
     die(); 
     } 
    } else { 
     $query = $this->db->get($tableName); 
    } 
    return $query->result(); 
} 
+0

Yeaa,但這意味着我(頁面= 0&per_page = 3,page = 3&per_page = 3,page = 6&per_page = 3) –

+0

對不起仍然不好(頁面= 1&per_page = 3)返回結果開始與3 –

+0

我編輯了代碼。爲params函數的$ start放置一個默認值。 – redfades