Home >Backend Development >PHP Tutorial >Example of how to implement infinite loop in PHP to obtain data in MySQL

Example of how to implement infinite loop in PHP to obtain data in MySQL

黄舟
黄舟Original
2017-08-22 09:21:162088browse

Recently, the company has a need to obtain data from MySQL, and then display it in a wireless loop on the page. In fact, this function can be realized through jq, or through php+mysql. The following editor will share with you the unlimited data based on PHP Friends who are interested can take a look at the implementation method of cyclically obtaining data in MySQL

Recently, the company has a need to obtain data from MySQL, and then display it in a wireless loop on the page. The main thing is to keep clicking a button, and then the data will cycle from the beginning to the end. If the data at the end is not enough, then take a few pieces from the beginning of the data to supplement it.

Actually, this function can be implemented through JQ or PHP + MYSQL, but JQ is more convenient and more efficient.

Display 10 pieces of data each time.


 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);
 }

The above sql statement uses the union all method of mysql to splice the two collections together and take the first ten pieces of data.


 public function getCount(){//获取数据的条数
     $sql="select count(id) as t from `mytable`";
     return $this->query($sql);
 }

The next step is to obtain the data in the controller and provide a data interface for ajax.


//测试数据库无限循环取数据
   public function getInfiniteData(){
    //用户点击数
    $page = $_GET['click'];
     //每次展示条数
    $pagesize = 10;
     //获取总条数
    $total = $this->Mydemo->get_count();
    $t = $total[0][0]['t'];
     //算出每次点击的其起始位置
    $limit = (($page - 1)*$pagesize)%$t;
    $data = $this->Mydemo->get_data($limit);
    if (!empty($data)) {
      //转换为二维数组
      $list = [];
      foreach ($data as $key => $v) {
        $list[$key] = $data[$key][0];
      }
      $info['msg'] = $list;
      $info['code'] = '001';
    }else{
      $info['code'] = '002';
      $info['msg'] = '暂无数据';
    }
    echo json_encode($info,JSON_UNESCAPED_UNICODE);die;
  }

Summary

The above is the detailed content of Example of how to implement infinite loop in PHP to obtain data in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn