分页的原理了解偏移量
$offset=num*(page-1);
本页数量*(页码-1);
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>最新影视简介</title> <style> body{ padding: 0; margin: 0; } caption{ margin: 10px; } table{ border-collapse: collapse; width: 90%; text-align: center; margin: 0 auto; } table,th,td{ border:1px solid black; } table thead tr{ background-color: lightgoldenrodyellow; } /*table tbody tr td:nth-last-of-type(1){*/ /* width: 10%;*/ /*}*/ ul{ text-align: center; } ul li{ list-style: none; display: inline-block; width: 30px; height: 20px; border: 1px solid black; text-align: center; margin-left: 10px; cursor: pointer; line-height: 20px; } ul li:hover{ background-color: lightblue; border: 1px solid red; } /*高亮显示*/ .active{ background-color: lightblue; border: 1px solid red; } </style> </head> <body onload="getData(<?php echo $_GET['p'] ?? 1; ?>)"> <table> <caption>最新影视剧介绍</caption> <thead> <tr> <th>序号</th> <th>片名</th> <th>简介</th> </tr> </thead> <tbody> </tbody> </table> <!-- 分页条--> <ul> </ul> <script> function getData(p){ //创建request对象 var request=new XMLHttpRequest(); //监听请求 request.onreadystatechange=function () { //请求成功 if (request.readyState===4){ // console.log(request.responseText); var data=JSON.parse(request.responseText); console.log(data); var ul=document.getElementsByTagName('ul').item(0); for (var i=0;i<data[0];i++){ var li=document.createElement('li'); li.innerHTML=(i+1); //高亮显示 var gl=location.search.slice(3,4); if(li.innerText===gl){ li.className='active'; }else{ li.className=null; } // li.className=(li.innerText===gl)? 'active':null; // if(gl===p){ // li.className='active'; // } //动态显示浏览器网址数据 li.onclick=function(){ var search = location.search.slice(0,3) + this.innerText; location.replace(search); }; ul.appendChild(li); } //2.显示表格内容 var tbody=document.getElementsByTagName('tbody').item(0); data[1].forEach(function (value){ var tr=document.createElement('tr'); for(var key in value ){ var td=document.createElement('td'); td.innerText=value[key]; tr.appendChild(td); } tbody.appendChild(tr); }) } }; //配置请求 request.open('GET', 'get_movies.php?p='+p.toString(), true); //发送请求 request.send(null); } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php //获取当前要显示的椰树 $page=intval($_GET['p']); $pdo = new PDO('mysql:dbname=php', 'root', '123456'); //每页显示数量 $num=5; //总页数:需要分二步,第一步求出总"记录数量" 第二总记录数量除以每页显示的记录数量 再向上取整 $sql= "SELECT CEIL(COUNT(`mov_id`)/{$num}) FROM `movies` "; $stmt=$pdo->prepare($sql); $stmt->execute(); $pages=$stmt->fetchColumn(0); //偏移量=当前显示数量*(当前页码-1) $offset=$num * ($page-1); $sql = "SELECT `mov_id`,`name`, CONCAT(LEFT(`detail`,20),'...') FROM `movies` LIMIT {$num} OFFSET {$offset} "; $stmt=$pdo->prepare($sql); $stmt->execute(); $result=$stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode([$pages,$result]);
运行实例 »
点击 "运行实例" 按钮查看在线实例