PHP uses MySQL data in an infinite loop ., Phpmysql
Recently, the company has a need to obtain data from MySQL, and then display the data on the page in a loop. It is mainly to keep clicking a button, and then the data starts from the beginning to the end. If the data at the end is not enough, then add several records from the beginning of the data.
In fact, this function can be implemented through JS + PHP, or through PHP + MYSQL + JS, but JS + PHP is more convenient and more efficient.
The following describes how to implement PHP + MYSQL + JS.
10 data entries are displayed at a time.
1 public function get_data($limit){2 $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";3 return $this->query($sql);4 }
The preceding SQL statement concatenates two sets using the union all method of mysql and obtains the first 10 pieces of data.
1 public function get_count () {// number of data records retrieved
2 $ SQL = "select count (id) as t from 'mytable '";
3 return $ this-> query ($ SQL );
4}
The next step is to obtain data in the Controller and provide the data interface for ajax.
1 // Test Database Infinite Loop Data 2 public function getInfiniteData () {3 // user clicks 4 $ page =$ _ GET ['click']; 5 // The number of items displayed each time is 6 $ pagesize = 10; 7 // get the total number of items 8 $ total = $ this-> Mydemo-> get_count (); 9 $ t = $ total [0] [0] ['T']; 10 // calculates the start position of each click. 11 $ limit = ($ page-1) * $ pagesize) % $ t; 12 13 $ data = $ this-> Mydemo-> get_data ($ limit); 14 15 if (! Empty ($ data) {16 // convert to a two-dimensional array 17 $ list = []; 18 foreach ($ data as $ key => $ v) {19 $ list [$ key] = $ data [$ key] [0]; 20} 21 22 $ info ['msg '] = $ list; 23 $ info ['code'] = '001'; 24} else {25 $ info ['code'] = '002 '; 26 $ info ['msg '] = 'no data temporarily'; 27} 28 echo json_encode ($ info, JSON_UNESCAPED_UNICODE); die; 29 30}
I will not post the JS Code.