最近公司有個(gè)需求需要從MySQL獲取數(shù)據(jù),然后在頁(yè)面上無線循環(huán)的翻頁(yè)展示。主要就是一直點(diǎn)擊一個(gè)按鈕,然后數(shù)據(jù)從最開始循環(huán)到末尾,如果末尾的數(shù)據(jù)不夠了,那么從數(shù)據(jù)的最開始取幾條補(bǔ)充上來。
其實(shí),這個(gè)功能可以通過JQ實(shí)現(xiàn),也可以通過PHP + MYSQL實(shí)現(xiàn),只不過JQ比較方便而且效率更高罷了。
每次顯示10條數(shù)據(jù)。
public function get_data($limit){ $sql="select * from ((select id,name from `mytable` limit {$limit},10) union all (select id,name from `mytable` limit 0,10)) as test limit 0,10"; return $this->query($sql); }
上述sql語句通過mysql的union all方法,把兩個(gè)集合拼接到一起,并取前十條數(shù)據(jù)。
public function getCount(){//獲取數(shù)據(jù)的條數(shù) $sql="select count(id) as t from `mytable`"; return $this->query($sql); }
下一步在控制器中獲取數(shù)據(jù),并給ajax提供數(shù)據(jù)接口。
//測(cè)試數(shù)據(jù)庫(kù)無限循環(huán)取數(shù)據(jù) public function getInfiniteData(){ //用戶點(diǎn)擊數(shù) $page = $_GET['click']; //每次展示條數(shù) $pagesize = 10; //獲取總條數(shù) $total = $this->Mydemo->get_count(); $t = $total[0][0]['t']; //算出每次點(diǎn)擊的其起始位置 $limit = (($page - 1)*$pagesize)%$t; $data = $this->Mydemo->get_data($limit); if (!empty($data)) { //轉(zhuǎn)換為二維數(shù)組 $list = []; foreach ($data as $key => $v) { $list[$key] = $data[$key][0]; } $info['msg'] = $list; $info['code'] = '001'; }else{ $info['code'] = '002'; $info['msg'] = '暫無數(shù)據(jù)'; } echo json_encode($info,JSON_UNESCAPED_UNICODE);die; }
總結(jié)
以上所述是小編給大家介紹的PHP無限循環(huán)獲取MySQL中的數(shù)據(jù)實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)綠夏網(wǎng)網(wǎng)站的支持!