PHP分页技术,内容较多,分成上一页下一页
- 格式:docx
- 大小:12.48 KB
- 文档页数:2
php实现⽹页上⼀页下⼀页翻页过程详解前⾔这⼏天做项⽬因为数据太多,需要对信息进⾏上下翻页展⽰,就⾃⼰写了翻页的代码⼤致功能就是页⾯只显⽰⼏条信息,按上⼀页、下⼀页切换内容,当显⽰第⼀页时上⼀页和⾸页选项不可选,当页⾯加载到最后⼀页时下⼀页和尾页选项不可选具体效果如下:实现代码1)原⽣PHP⽅法先说⼀下总思路吧,⾸先我们要查询所有符合条件需要进⾏分页的总数据,计算展⽰的总页数。
然后获取当前显⽰的是第⼏页信息,⽤当前页数每页数据条数表⽰为总数据的第⼏条,再根据限制条件查询出当前页所需显⽰出来的数据。
将每⼀条数据echo替换HTML结构内容中,最后显⽰出来关于分页的限制条件很简单,只要查询到当前页为第1页时,⾸页和上⼀页选项跳转链接都固定在第⼀页同时设置选项disabled不可选,尾页也是相同的步骤。
具体代码如下:当前页cPage需要传过来,我的办法是初始cPage=0list.php*<a href="listmore.php?cPage=0" rel="external nofollow" rel="external nofollow" class="pull-right">更多>></a>$row=$table->fetch()每次读取⼀条信息,得到的是⼀个索引数组,代码⾥的$row['id']表⽰$row⾥⾯名为id的值,也可表⽰为$row.idconnect.php(连接数据库)<?php$link=new PDO("mysql:host=localhost;port=3306;dbname=db","root","");$link->query("set names utf8");listmore.php<ul id="list" class="media-list"><?phpinclude_once('connect.php');$result = $link->query("select * from news");$total=$result->rowCount();//查询出来符合条件的总数$pages=ceil($total/4);//分页的总页数$num = 4;//每页显⽰的数据条数$cPage = $_GET['cPage'];//获取当前是显⽰的第⼏页$start = $cPage * $num;//第⼀条数据$table = $link->query("select * from news order by id desc limit {$start},$num");$link = null;//销毁while ($row=$table->fetch()){//每次读出⼀条数据,赋给$row//插⼊多⾏⽂本,把值替换掉echo <<<_<li class="media"><a href="detail.php?id={$row['id']}"><img class="pull-left" src="{$row['src']}"><figcaption><h4><span class="title">{$row['title']}</span> <span class="news-date">{$row['time']}</span></h4><p>{$row['content']}</p></figcaption></a></li>_;}></ul>上下翻页:<div class="page text-center"><ul class="pagination" id="page"><li data-i="0" id="index" class="<?php if ($cPage==0) echo 'disabled'; ?>"><a href="listmore.php?cPage=0">«⾸页</a></li><li data-i="1" class="<?php if ($cPage==0) echo 'disabled';?>"><a href="listmore.php?cPage=<?php echo $cPage>0?$cPage-1:0?>"><上⼀页</a></li><li data-i="2" class="<?php if ($cPage==$pages-1) echo 'disabled'?>"><a href="listmore.php?cPage=<?php echo $cPage==($pages-1)?$pages-1:$cPage+1?>">下⼀页></a></li> <li data-i="3" id="end" class="<?php if ($cPage==$pages-1) echo 'disabled'?>"><a href="listmore.php?cPage=<?php echo $pages-1?>">尾页»</a></li><li class="disabled"><a href="##" id="total"><?php echo ($cPage+1)?>/<?php echo "$pages"?></a></li></ul></div>2)ajax⽅法HTML代码,展⽰信息装在panel-body⾥⾯<div class="panel-body" id="content"><ul id="list" class="media-list"></ul></div><div class="page text-center"><ul class="pagination" id="page"><li data-i="0" id="index" class="disabled"><a href="##">«⾸页</a></li><li data-i="1" class="disabled"><a href="##"><上⼀页</a></li><li data-i="2"><a href="##">下⼀页></a></li><li data-i="3" id="end"><a href="##">尾页»</a></li><li class="disabled"><a href="##" id="total"></a></li></ul></div><template id="temp"> //引⽤模板<li class="media"><a href="detail.html?id={id}"><img class="pull-left" src="{src}"><figcaption><h4><span class="title">{title}</span> <span class="news-date">{date}</span></h4> <p>{content}</p></figcaption></a></li></template>JS代码:var html=$('#temp').html();var curPage=0,pages=0;$.getJSON('php/pages.php',function (res) {pages=Math.ceil(res/4);/*获取信息的总页数*/});function show(cPage){//替换每⼀页的内容$.getJSON('php/listmore.php',{cPage:cPage},function (json) {var str='';$('#list').empty();json.forEach(function (el) {str+=html.replace('{id}',el.id).replace('{title}',el.title).replace('{src}',el.src).replace('{content}',el.content).replace('{date}',el.time);});$('#list').html(str);});$('#total').html((curPage+1)+'/'+pages);}setTimeout(function () {show(0);},100);$('#page').on('click','li',function () {//上下翻页,翻遍当前页的值var i=$(this).data('i');//jquery⾥特有的获取data-*属性的⽅法switch (i){case 0:curPage=0;break;case 1:curPage>0?curPage--:0;break;case 2:curPage<(pages-1)?curPage++:pages-1;break;case 3:curPage=pages-1;break;}show(curPage);disabled(curPage);})function disabled(curPage) {//关于临界值禁⽌选择if (curPage==0){/*当前页为第⼀页,⾸页和上⼀页选项禁⽌点击*/$('#index').addClass('disabled').next().addClass('disabled');$('#end').removeClass('disabled').prev().removeClass('disabled');} else if (curPage==pages-1){$('#index').removeClass('disabled').next().removeClass('disabled');$('#end').addClass('disabled').prev().addClass('disabled');} else {/*当前页为最后⼀页,尾页和下⼀页选项禁⽌点击*/$('#index').removeClass('disabled').next().removeClass('disabled');$('#end').removeClass('disabled').prev().removeClass('disabled');}}connect.php(连接数据库)<?php$link=new PDO("mysql:host=localhost;port=3306;dbname=db","root","");$link->query("set names utf8");pages.php(获取总页数)<?phpinclude_once('connect.php');//连接数据库$result = $link->query("select * from news");$row=$result->rowCount();echo $row;listmore.php(获取数据库⾥的数据)<?phpinclude_once ('connect.php');$num = 4;//每⼀页显⽰的数据条数$cPage = $_GET['cPage'];//获取当前页$start = $cPage * $num;//计算当前页显⽰的第⼀条数据的数⽬/*从表中查询从开始$start的⼀共$num条数据*/$result = $link->query("select * from news order by id desc limit {$start},$num");$link = null;while ($row=$result->fetch()){/*每⼀次读取⼀条数据*/$json[]=$row;/*把数据赋给json数组*/}echo json_encode($json);/*把json数组以json格式返回给HTML*/以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
PHP分页效果实现调用方法//$currentPage 当前页//$pageSize 每页条数//$sql SQL语句select colum1,colum2,... from table1 limit 0,10;//$url 链接地址//$params 分页参数相关数组array("key1":"value1","key2":"value2",...);//$isChangePageSize 是否可修改每页条数true/falseinclude(‘fenye.php’);//引用分页类<?php new ZCFenyeAction($currentPage,$pageSize,$sql,$url,$params,$isChangePageSize);//分页?>分页类fenye.php<?php/**分页@author ZC*/class ZCFenyeAction{/**分页构造函数*/function __construct($currentPage,$pageSize,$sql,$url,$params,$isChangePageSize){echo $this->fenye($currentPage,$pageSize,$sql,$url,$params,$isChangePageSize);}/**分页方法@param currentPage 当前页@param pageSize 每页条数@param totalNumber 总条数@param $url; 链接地址@param $params; 分页参数相关数组array("key1"=>value1,"key2"=>value2,...);@param isChangePageSize 是否可修改每页条数true/false@return str form表单字符串*/function fenye($currentPage,$pageSize,$sql,$url,$params,$isChangePageSize){//form表单字符串$str = "<form method=\"post\" name=\"zcform\">";//总条数$totalNumber = $this->getTotalNumber($sql);$str .= "<input type=\"hidden\" name=\"totalNumbe\" id=\"totalNumber\" value=\"$totalNumber\" />";//总页数$totalPage = ceil((float)$totalNumber/(float)$pageSize);//共几条$str .= "共<span style=\"color:#FF0000\" >$totalNumber</span>条 ";//每页显示条数$str .= $this->pageSize($pageSize,$currentPage,$isChangePageSize);//第当前页/总页数页$str .= "第<span style=\"color:#FF0000\" >$currentPage/$totalPage</span>页 ";//分页样式$str .= $this->fenyeStyle($currentPage,$pageSize,$totalNumber,$totalPage);//转到第几页$str .= $this->goto($totalPage,$currentPage);//确定$str.="<input type='button' value='GO' onclick=\"submitForm(-1);\" style=\"height:16px; width:30px; text-align:center; cursor:pointer; \" />";//链接地址$str .= "<input type=\"hidden\" name=\"url\" id=\"url\" value=\"$url\" />";//分页参数$str .= $this->params($params);$str .= "</from>";return $str;}/**获取总条数@param sql sql语句@return totalNumber 总条数*/function getTotalNumber($sql){$totalNumber = 0;$sql = $this->getTotalNumberSQL($sql);$query = mysql_query($sql);if($query > 0){$row = mysql_fetch_array($query);$totalNumber = $row["cts"];}return $totalNumber;}/**获取总条数的SQL语句@param sql sql语句@return sql sql语句*/function getTotalNumberSQL($sql){$newsql = "select count(*) as cts ";$start = stripos($sql," from ");$end = stripos($sql," limit ");$newsql .= substr($sql,$start,($end - $start));return $newsql;}/**每页显示条数*/function pageSize($pageSize,$currentPage,$isChangePageSize){$str .= "每页显示<input tpye=\"text\" name=\"pageSize\" id=\"pageSize\" value=\"$pageSize\" ";if(!$isChangePageSize){$str.=" readonly=\"readonly\" ";}$str.=" style=\"height:14px; width:20px; text-align:center; color:#FF0000; \"/>条 ";return $str;}/**转到第几页*/function goto($totalPage,$currentPage){$str .= "转到<input tpye=\"text\" name=\"currentPage\" id=\"currentPage\" value=\"$currentPage\" ";$str.=" style=\"height:14px; width:30px; text-align:center; color:#FF0000; \"/>页 ";return $str;}/**分页参数*/function params($params){$str = "";if($params != null){foreach($params as $key => $value){$str .= "<input type=\"hidden\" name=\"$key\" id=\"$key\" value=\"$value\" />";}}return $str;}/**分页样式:共100条记录,每页显示10条,当前第1/10页[首页] [上页] [下页] [尾页] 跳转到1 页*/function fenyeStyle($currentPage,$pageSize,$totalNumber,$totalPage){$str = "";//首页if($currentPage <= 1){$str .= "首页 ";}//上一页if($currentPage > 1){$str .= "<a href=\"javascript:;\" onclick=\"submitForm(1)\">[首页]</a> ";$str .= "<a href=\"javascript:;\" onclick=\"submitForm(".($currentPage-1).")\">上一页</a> ";}//下一页if($currentPage < $totalPage) {$str .= "<a href=\"javascript:;\" onclick=\"submitForm(".($currentPage+1).")\">下一页</a> ";$str .= "<a href=\"javascript:;\" onclick=\"submitForm($totalPage)\">[尾页]</a> ";}if($currentPage == $totalPage){$str .= "尾页 ";}return $str;}}?><script type="text/javascript"><!--function submitForm(currentPage){var pageSize = document.getElementById("pageSize").value;if(currentPage == -1){currentPage = document.getElementById("currentPage").value;}var totalNumber = document.getElementById("totalNumber").value;var re=/^[0-9]*[1-9][0-9]*$/;if(!re.test(pageSize)){alert("每页显示条数有误!");document.getElementById("pageSize").value = 1;return;}if(!re.test(currentPage)){alert("跳转页数有误!");document.getElementById("currentPage").value = 1;return;}var totalPage = Math.ceil(parseFloat(totalNumber)/parseFloat(pageSize));//总页数if(currentPage > totalPage){alert("跳转页数超出了页数范围!");document.getElementById("currentPage").value = 1;return;}document.getElementById("currentPage").value = currentPage;//保存当前页document.zcform.action = document.getElementById("url").value;document.zcform.submit();}//--></script>。
php分页类的使用方法PHP分页类是一个比较有用的类,如何灵活的运用这个类来帮助我们完成功能的实现是一个程序员必备的知识。
下面由店铺整理了几种php分页类的使用方法,希望对大家有所帮助。
php分页类的使用方法(一)<?php/*分页类用于实现对多条数据分页显示version:1.0Date:2013-10-20*//*调用非常方便,先连接好数据库,直接传人查询的sql字符串即可,也可以指定每页显示的数据条数例如$pages = new Page('SELECT * FROM `zy_common_member`');或$pages = new Page('SELECT * FROM `zy_common_member`', 10);*/class Page{private $curPage;private $totalPages;//数据总共分多少页显示private $dispNum;//每页显示的数据条数private $queryStr;//查询的SQL语句private $limitStr;//查询语句后面的limit控制语句/*构造函数$queryStr 查询数据的SQL语句$dispNum 每页显示的数据条数*/public function __construct($queryStr='',$dispNum=10){$result = mysql_query($queryStr);$totalNum = mysql_num_rows($result);$this->dispNum = $dispNum;$this->totalPages = ceil($totalNum / $dispNum);$this->queryStr = $queryStr;$temp = (isset($_GET["curPage"]) ? $_GET["curPage"] : 1);$this->setCurPage($temp);$this->showCurPage();$this->showFoot();}/*显示当前页的数据内容*/private function showCurPage(){$this->limitStr = ' LIMIT '.(($this->curPage - 1)* $this->dispNum).','.$this->dispNum;//echo $this->queryStr.$this->limitStr;$result = mysql_query($this->queryStr.$this->limitStr);if (!$result){if ($this->totalPages > 0){echo '查询出错'.'<br>';}else{echo '无数据'.'<br>';}return;}$cols = mysql_num_fields($result); echo '<table border="1">';echo '<tr>';for($i=0; $i<$cols; $i++){echo '<th>';echo mysql_field_name($result, $i); echo '</th>';}echo '</tr>';while($row = mysql_fetch_assoc($result)) {echo '<tr>';foreach($row as $key=>$value){echo '<td>';echo $value;echo '</td>';}echo '</tr>';}echo '</table>';}private function setCurPage($curPage){ if($curPage < 1){$curPage = 1;}else if($curPage > $this->totalPages) {$curPage = $this->totalPages;}$this->curPage = $curPage;}/*显示分页页脚的信息如首页,上一页,下一页,尾页等信息*/private function showFoot(){echo '<a href="?curPage=1">首页</a>';echo '<a href="?curPage='.($this->curPage - 1).'">上一页</a>';echo '<a href="?curPage='.($this->curPage + 1).'">下一页</a>';echo '<a href="?curPage='.$this->totalPages.'">尾页</a>';}}>php分页类的使用方法(二)< ?php//为了避免重复包含文件而造成错误,加了判断函数是否存在的条件:if(!function_exists(pageft)){//定义函数pageft(),三个参数的含义为://$totle:信息总数;//$displaypg:每页显示信息数,这里设置为默认是20;//$url:分页导航中的链接,除了加入不同的查询信息“page”外的部分都与这个URL相同。
php 分页计算公式PHP分页计算公式是指在PHP编程中,用于计算分页的公式。
分页是指将大量数据按照一定的规则分为多个页面显示,常用于网站的数据展示和浏览。
在开发网站时,经常需要使用分页功能来提高用户体验和减少数据加载的压力。
在PHP中,常用的分页计算公式如下:1. 计算总页数总页数 = 总记录数 / 每页显示的记录数2. 计算起始记录位置起始记录位置 = (当前页码 - 1) * 每页显示的记录数3. 判断是否有上一页有上一页 = 当前页码 > 14. 判断是否有下一页有下一页 = 当前页码 < 总页数通过使用这些分页计算公式,可以实现在PHP中进行数据分页的功能。
下面将详细介绍如何使用这些公式实现分页功能。
需要获取总记录数和每页显示的记录数。
总记录数可以通过查询数据库、读取文件等方式获得,每页显示的记录数一般可以根据需求进行设定。
然后,需要获取当前页码。
当前页码可以通过URL参数、表单提交等方式获得,需要注意对用户输入的合法性进行校验,避免非法输入导致错误。
接下来,可以根据总记录数和每页显示的记录数计算出总页数。
需要注意处理除不尽的情况,可以使用向上取整的方式保证总页数的准确性。
然后,可以根据当前页码和每页显示的记录数计算出起始记录位置。
起始记录位置决定了每页显示的数据的起始位置,通过在查询数据库时添加LIMIT子句,可以从指定位置开始获取数据。
根据当前页码和总页数判断是否有上一页和下一页。
如果当前页码大于1,则说明存在上一页;如果当前页码小于总页数,则说明存在下一页。
在实现分页功能时,还需要注意处理边界情况。
例如,当总记录数为0时,应该禁用上一页和下一页的链接;当只有一页时,不显示分页导航等。
PHP分页计算公式是开发网站中常用的公式,可以帮助实现数据分页的功能。
通过合理使用这些公式,可以提高用户体验和减少数据加载的压力。
在实际应用中,需要根据具体需求进行调整和优化,以达到最佳的效果。
PHP中常用的分页类总结分页是目前在显示大量结果时所采用的最好的方式。
有了下面这些代码的帮助,开发人员可以在多个页面中显示大量的数据。
在互联网上,分页是一般用于搜索结果或是浏览全部信息php基本分页代码如下复制代码<?php// database connection info$conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL",E_USER_ERROR);$db = mysql_select_db('dbname',$conn) or trigger_error("SQL", E_USER_ERROR);// find out how many rows are in the table$sql = "SELECT COUNT(*) FROM numbers";$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);$r = mysql_fetch_row($result);$numrows = $r[0];// number of rows to show per page$rowsperpage = 10;// find out total pages$totalpages = ceil($numrows / $rowsperpage);// get the current page or set a defaultif (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {// cast var as int$currentpage = (int) $_GET['currentpage'];} else {// default page num$currentpage = 1;} // end if// if current page is greater than total pages...if ($currentpage > $totalpages) {// set current page to last page$currentpage = $totalpages;} // end if// if current page is less than first page...if ($currentpage < 1) {// set current page to first page$currentpage = 1;} // end if// the offset of the list, based on current page$offset = ($currentpage - 1) * $rowsperpage;// get the info from the db$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); // while there are rows to be fetched...while ($list = mysql_fetch_assoc($result)) {// echo dataecho $list['id'] . " : " . $list['number'] . "<br />";} // end while/****** build the pagination links ******/// range of num links to show$range = 3;// if not on page 1, don't show back linksif ($currentpage > 1) {// show << link to go back to page 1echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";// get previous page num$prevpage = $currentpage - 1;// show < link to go back to 1 pageecho " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> "; } // end if// loop to show links to range of pages around current pagefor ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number...if (($x > 0) && ($x <= $totalpages)) {// if we're on current page...if ($x == $currentpage) {// 'highlight' it but don't make a linkecho " [<b>$x</b>] ";// if not current page...} else {// make it a linkecho " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";} // end else} // end if} // end for// if not on last page, show forward and last page linksif ($currentpage != $totalpages) {// get next page$nextpage = $currentpage + 1;// echo forward link for next pageecho " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";// echo forward link for lastpageecho " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";} // end if/****** end build pagination links ******/?>先看一个常用的php分页类代码如下复制代码<?php/*Place code to connect to your DB here.*/include('config.php'); // include your code to connect to DB.$tbl_name=""; //your table name// How many adjacent pages should be shown on each side?$adjacents = 3;/*First get total number of rows in data table.If you have a WHERE clause in your query, make sure you mirror it here.*/$query = "SELECT COUNT(*) as num FROM $tbl_name";$total_pages = mysql_fetch_array(mysql_query($query));$total_pages = $total_pages[num];/* Setup vars for query. */$targetpage = "filename.php"; //your file name (the name of this file)$limit = 2; //how many items to show per page$page = $_GET['page'];if($page)$start = ($page - 1) * $limit; //first item to display on this pageelse$start = 0; //if no page var is given, set start to 0/* Get data. */$sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";$result = mysql_query($sql);/* Setup page vars for display. */if ($page == 0) $page = 1; //if no page var is given, default to 1.$prev = $page - 1; //previous page is page - 1$next = $page + 1; //next page is page + 1$lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1/*Now we apply our rules and draw the pagination object.We're actually saving the code to a variable in case we want to draw it more than once.*/$pagination = "";if($lastpage > 1){$pagination .= "<div class="pagination">";//previous buttonif ($page > 1)$pagination.= "<a href="$targetpage?page=$prev">� previous</a>";else$pagination.= "<span class="disabled">� previous</span>";//pagesif ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up {for ($counter = 1; $counter <= $lastpage; $counter++){if ($counter == $page)$pagination.= "<span class="current">$counter</span>";else$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";}}elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some{//close to beginning; only hide later pagesif($page < 1 + ($adjacents * 2)){for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++){if ($counter == $page)$pagination.= "<span class="current">$counter</span>";else$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";}$pagination.= "...";$pagination.= "<a href="$etpage?page=$lpm1">$lpm1</a>"; $pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";}//in middle; hide some front and some backelseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)){$pagination.= "<a href="$targetpage?page=1">1</a>";$pagination.= "<a href="$targetpage?page=2">2</a>";$pagination.= "...";for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++){if ($counter == $page)$pagination.= "<span class="current">$counter</span>";else$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";}$pagination.= "...";$pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";$pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";}//close to end; only hide early pageselse{$pagination.= "<a href="$targetpage?page=1">1</a>";$pagination.= "<a href="$targetpage?page=2">2</a>";$pagination.= "...";for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {if ($counter == $page)$pagination.= "<span class="current">$counter</span>";else$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";}}}//next buttonif ($page < $counter - 1)$pagination.= "<a href="$targetpage?page=$next">next �</a>";else$pagination.= "<span class="disabled">next �</span>";$pagination.= "</div>n";}?><?phpwhile($row = mysql_fetch_array($result)){// Your while loop here}?><?=$pagination?>实例代码如下复制代码<?phpclass PageView{/**页码**/public $pageNo = 1;/**页大小**/public $pageSize = 20;/**共多少页**/public $pageCount = 0;/**总记录数**/public $totalNum = 0;/**偏移量,当前页起始行**/public $offSet = 0;/**每页数据**/public $pageData = array();/**是否有上一页**/public $hasPrePage = true;/**是否有下一页**/public $hasNextPage = true;public $pageNoList = array();public $jsFunction ='jsFunction';/**** @param unknown_type $count 总行数* @param unknown_type $size 分页大小* @param unknown_type $string*/public function __construct($count=0, $size=20,$pageNo=1,$pageData=array(),$jsFunction='jsFunction'){$this->totalNum = $count;//总记录数$this->pageSize = $size;//每页大小$this->pageNo = $pageNo;//计算总页数$this->pageCount = ceil($this->totalNum/$this->pageSize);$this->pageCount = ($this->pageCount<=0)?1:$this->pageCount;//检查pageNo$this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;$this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;//计算偏移$this->offset = ( $this->pageNo - 1 ) * $this->pageSize;//计算是否有上一页下一页$this->hasPrePage = $this->pageNo == 1 ?false:true;$this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;$this->pageData = $pageData;$this->jsFunction = $jsFunction;}/*** 分页算法* @return*/private function generatePageList(){$pageList = array();if($this->pageCount <= 9){for($i=0;$i<$this->pageCount;$i++){array_push($pageList,$i+1);}}else{if($this->pageNo <= 4){for($i=0;$i<5;$i++){array_push($pageList,$i+1);}array_push($pageList,-1);array_push($pageList,$this->pageCount);}else if($this->pageNo > $this->pageCount - 4){array_push($pageList,1);array_push($pageList,-1);for($i=5;$i>0;$i--){array_push($pageList,$this->pageCount - $i+1);}}else if($this->pageNo > 4 && $this->pageNo <= $this->pageCount - 4){ array_push($pageList,1);array_push($pageList,-1);array_push($pageList,$this->pageNo -2);array_push($pageList,$this->pageNo -1);array_push($pageList,$this->pageNo);array_push($pageList,$this->pageNo + 1);array_push($pageList,$this->pageNo + 2);array_push($pageList,-1);array_push($pageList,$this->pageCount);}}return $pageList;}/**** 创建分页控件* @param* @return String*/public function echoPageAsDiv(){$pageList = $this->generatePageList();$pageString ="<div class='pagination'><div class='page-bottom'>";if(!empty($pageList)){if($this->pageCount >1){if($this->hasPrePage){$pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo-1) . ")">上一页</a>";}foreach ($pageList as $k=>$p){if($this->pageNo == $p){$pageString = $pageString ."<span class='page-cur'>" . $this->pageNo . "</span>";continue;}if($p == -1){$pageString = $pageString ."<span class='page-break'>...</span>";continue;}$pageString = $pageString ."<a href="javascript:" .$this->jsFunction . "(" . $p .")">" . $p . "</a>";}if($this->hasNextPage){$pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo+1) . ")">下一页</a>";}}}$pageString = $pageString .("</div></div>");return $pageString;}}?>css代码>y: Tahoma;overflow: hidden; padding-top: 12px; text-align: center;}gin-bottom: 20px;}ur, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-break, . k;font-family: Tahoma,SimSun,Arial; height: 22px;line-height:22px; margin: 0; min-width: 16px;padding: 0 5px; text-align: center; v}tion .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-cur, .pagination .p ed3d83; color:#e9357d; font-weight:bold;}border: 1px solid #ed3d83;text-decoration: none; background-color:#f95f9d; color:#fff;}v_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g { width: 36px; background-image:ge.gif);}v { background-position: -0px -38px; padding-left: 16px;}v_g { background-position:0px -59px; padding-left: 16px; color:#cbcbcb; font-weight:normal;}t { background-position: 0px 0px; padding-right: 16px; font-weight:normal;}t_g { background-position: -0px -19px; padding-right: 16px; color:#cbcbcb;}{background-color: #f95f9d; border: 1px solid #ed3d83;color: #fff;font-weight: bold;}ak {border: medium none; background:none transparent; color:#333;}在php页面中的调用方法代码如下复制代码$pageNo = $_GET['pageNo'];if(empty($pageNo)){$pageNo = 1;}//分页数据$pageData = News::getNewsPage($pageNo,$pageSize);//取得总行数$count = News::getNewsCount();//创建分页器$p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);//生成页码$pageViewString = $p->echoPageAsDiv();。
php实现分页功能的3种⽅法直接上代码,希望⼤家仔细阅读。
⽅法⼀:讲sql查询进⾏分页进⾏,需要调⽤⼏个函数,具体见脚本:1.pager.class.php<?phpclass pager {public $sql; //SQL查询语句public $datanum; //查询所有的数据总记录数public $page_size; //每页显⽰记录的条数protected $_errstr;protected $_conn;protected $_query_id;public function query($query)///这个函数有问题,暂时可以不⽤{$ret = false;if (!empty($query)) {if ($this->_conn === false || !is_resource($this->_conn)) {warningLog(__METHOD__ . ': query sql with no connection', true);return false;}$this->_query_id = @mysql_query($query, $this->_conn);if ($this->_query_id === false) {$this->_errstr = @mysql_error();$ret = false;} else {$this->_errstr = 'SUCCESS';$ret = $this->_query_id;}}$msg = ($ret === false) ? 'false' : strval($ret);debugLog(__METHOD__.": [$msg] returned for sql query [$query]");return $ret;}function __construct($sql,$page_size) {$result = mysql_query($sql);$datanum = mysql_num_rows($result);$this->sql=$sql;$this->datanum=$datanum;$this->page_size=$page_size;}//当前页数public function page_id() {if($_SERVER['QUERY_STRING'] == ""){return 1;}elseif(substr_count($_SERVER['QUERY_STRING'],"page_id=") == 0){return 1;}else{return intval(substr($_SERVER['QUERY_STRING'],8));}}//剩余url值public function url() {if($_SERVER['QUERY_STRING'] == ""){return "";}elseif(substr_count($_SERVER['QUERY_STRING'],"page_id=") == 0){return "&".$_SERVER['QUERY_STRING'];}else{return str_replace("page_id=".$this->page_id(),"",$_SERVER['QUERY_STRING']);}}//总页数public function page_num() {if($this->datanum == 0){return 1;}else{return ceil($this->datanum/$this->page_size);}}//数据库查询的偏移量public function start() {return ($this->page_id()-1)*$this->page_size;}//数据输出public function sqlquery() {return $this->sql." limit ".$this->start().",".$this->page_size;}//获取当前⽂件名private function php_self() {return $_SERVER['PHP_SELF'];}//上⼀页private function pre_page() {if ($this->page_id() == 1) { //页数等于1return "<a href=".$this->php_self()."?page_id=1".$this->url().">上⼀页</a> ";}elseif ($this->page_id() != 1) { //页数不等于1return "<a href=".$this->php_self()."?page_id=".($this->page_id()-1).$this->url().">上⼀页</a> ";}}//显⽰分页private function display_page() {$display_page = "";if($this->page_num() <= 10){ //⼩于10页for ($i=1;$i<=$this->page_num();$i++) //循环显⽰出页⾯$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";return $display_page;}elseif($this->page_num() > 10){ //⼤于10页if($this->page_id() <= 6){for ($i=1;$i<=10;$i++) //循环显⽰出页⾯$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";return $display_page;}elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id() >= 4)){for ($i=$this->page_id()-5;$i<=$this->page_id()+4;$i++) //循环显⽰出页⾯$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";return $display_page;}elseif(($this->page_id() > 6) && ($this->page_num()-$this->page_id() < 4)){for ($i=$this->page_num()-9;$i<=$this->page_num();$i++) //循环显⽰出页⾯$display_page .= "<a href=".$this->php_self()."?page_id=".$i.$this->url().">".$i."</a> ";return $display_page;}}}//下⼀页private function next_page() {if ($this->page_id() < $this->page_num()) { //页数⼩于总页数return "<a href=".$this->php_self()."?page_id=".($this->page_id()+1).$this->url().">下⼀页</a> "; }elseif ($this->page_id() == $this->page_num()) { //页数等于总页数return "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url().">下⼀页</a> ";}}// 设置分页信息public function set_page_info() {$page_info = "共".$this->datanum."条 ";$page_info .= "<a href=".$this->php_self()."?page_id=1".$this->url().">⾸页</a> ";$page_info .= $this->pre_page();$page_info .= $this->display_page();$page_info .= $this->next_page();$page_info .= "<a href=".$this->php_self()."?page_id=".$this->page_num().$this->url().">尾页</a> "; $page_info .= "第".$this->page_id()."/".$this->page_num()."页";return $page_info;}}>2.脚本2:<?php//类的⽤法// 读取分页类include("pager.class.php");// 数据库连接初始化// $db = new mysql();$impeach_host = '10.81.43.139';$impeach_usr = 'vmtest15';$impeach_passwd = 'vmtest15';$impeach_name = 'ufeature';$impeach_con = mysql_connect($impeach_host, $impeach_usr, $impeach_passwd) ordie("Can't connect ".mysql_error());mysql_select_db($impeach_name, $impeach_con);// 这是⼀个sql查询语句,并得到查询结果$sql = "select word from ufeature.spam_accuse_word_list where flag='0'";// 分页初始化$page = new pager($sql,20);// 20是每页显⽰的数量// $res_1 = mysql_query($sql) or// die("Can't get result ".mysql_error());$result=mysql_query($page->sqlquery());while($info = mysql_fetch_array($result,MYSQL_ASSOC)){// while($info = mysql_fetch_array($res_1, MYSQL_ASSOC)){echo $info["word"]."<br/>";}// 页码索引条echo $page->set_page_info();>⽅法⼆:使⽤ajax的⽅法1、⾸先了解SQL语句中的limit⽤法SELECT * FROM table …… limit 开始位置,操作条数(其中开始位置是从0开始的)例⼦取前20条记录:SELECT * FROM table …… limit 0 , 20从第11条开始取20条记录:SELECT * FROM table …… limit 10 , 20LIMIT n 等价于 LIMIT 0,n。
thinkphp5.1 分页使用实例一、概述ThinkPHP5.1是一款流行的PHP框架,提供了许多方便的功能和组件,其中之一就是分页功能。
本篇文章将介绍如何在ThinkPHP5.1中使用分页,以及如何在实际应用中进行分页操作。
二、分页原理分页是网站中常见的需求,通过分页可以方便地展示大量数据,同时避免页面加载过慢的问题。
在ThinkPHP5.1中,分页的实现原理主要是通过查询结果集的分段处理来实现的。
通过设置每页显示的数据量,系统会自动计算出当前页需要的数据范围,并返回给用户。
三、分页使用步骤1. 引入分页组件:在ThinkPHP5.1中,分页功能是由第三方组件提供的,需要在项目中引入该组件。
可以通过在文件顶部添加以下代码来引入分页组件:```phpuse think\facade\View;use think\facade\Db;```2. 查询数据并设置分页参数:在获取数据之前,需要先设置分页参数,包括当前页码、每页显示的数据量等。
可以通过以下代码来设置分页参数:```php$page = 2; // 当前页码$size = 5; // 每页显示的数据量$result = Db::name('table_name')->paginate($page, $size) // 使用分页方法获取数据->setField('order_by', 'column_name'); // 设置排序字段(可选)```其中,`table_name`是要查询的表名,`column_name`是排序字段名。
通过调用`paginate`方法,系统会自动处理分页逻辑,并返回一个包含当前页数据的对象。
3. 渲染分页视图:将分页数据传递给视图文件,进行展示。
可以使用以下代码将分页数据传递给视图文件:```phpreturn View::fetch('page', ['data' => $result]); // 获取分页数据并传递给视图文件```在视图中,可以使用模板标签来显示分页信息和数据内容。
php 分页技术详细代码2010.10.30(2010-10-30 13:53:34)转载▼标签:itphp分页技术今天写了一个php分页代码贴出来不是为了炫耀,而是希望和大家交流技。
总共2个页面, conn.php 连接数据可和 student.php 负责显示学生信息。
我在数据库fenye里面的建的stu这个表总共有6个字段如下:做出的效果如下面的,不是很好看,只求分页效果,需要的可以自己美化。
数据库我插入了6条记录,每页显示3调剂了,所以只有2页。
做出的效果如下面的,不是很好看,只求分页效果,需要的可以自己美化。
做出的效果如下面的,不是很好看,只求分页效果。
下面是conn.php的代码,我的数据库密码不一定和你的一样哦。
<?php$conn=mysql_connect('localhost','root','root') or die ('mysql connect error:');mysql_select_db('student',$conn);mysql_query("SET NAMES utf8");echo "数据库连接成功";?>下面是student.php的代码<?phpinclude("conn.php");$pagenum=3;$page=$_GET['page'];$query=mysql_query("SELECT * FROM stu");$totalnum=mysql_num_rows($query);//统计表的总记录数$totalpage=ceil($totalnum/$pagenum);//计算表总分页数if(!isset($page)){$page=1;}$startcount=($page-1)*$pagenum;//计算当前页数的索引$sql="SELECT * FROM stu order by stu_id limit $startcount,$pagenum"; $stu_query=mysql_query($sql);?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>学生信息页</title></head><body><table width="650" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td colspan="6"><div align="center">学生信息管理</div></td></tr><tr><td align="center">编号</td><td align="center">学号</td><td align="center">姓名</td><td align="center">性别</td><td align="center">注册时间</td><td align="center">操作</td></tr><?php while(($array=mysql_fetch_array($stu_query))>0) //如果有记录 {?><tr><td align="center"><?php echo $array['stu_id']; ?></td><td align="center"><?php echo $array['stu_no']; ?></td><td align="center"><?php echo $array['stu_name']; ?></td><td align="center"><?php echo $array['stu_sex']; ?></td><td align="center"><?php echo $array['stu_data']; ?></td><td align="center">修改删除</td></tr><?php }?></table><table width="650" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td><div align="center"><?php if($page==1){?>首页上页<?php }else{$prev=$page -1;?><a href="?page=1">首页</a><a href="?page=<?php echo $prev;?>">上页</a><?php }?><?phpfor($i=1;$i<=$totalpage;$i++){?><a href="?page=<?php echo $i;?>"> <?php echo $i;?> </a><?php}?><?php if($page<=$totalpage) {$next=$page +1;?><a href="?page=<?php echo $next ;?>">下页</a><a href="?page=<?php echo $totalpage?>"> 末页</a><?php }else{ ?>下页末页<?php }?>共 <?php echo"$totalpage"; ?>页当前第<font color="#FF0000"><?php echo $page; ?></font>页总<?php echo"$totalnum"; ?>条记录</div></td></tr></table></body>。
翻页步骤1.每页显示多少条:已知2.一共多少条:数据表中一共条数(带条件)。
使用count(*)3.一共多少页:计算出来4.循环出分页代码:组装成链接形式5.当前页,从第几条开始:(当前页码-1)*每页显示多少条翻页类使用方法require_once(dirname(__FILE__)."/lib/page.php");require_once(dirname(__FILE__)."/lib/mysql.php");$dbMysql=MySQL::getInstance('127.0.0.1:3306','root','','myweb');$showNum=2;//每页显示多少条$sql="select count(*) as countAs from news";//查询一个多少条$allNum=$dbMysql->getRowsRst($sql);$allNum=$allNum['countAs'];$page=new page($showNum,$allNum,6);//实例化翻页类$pageHtml=$page->getCode();//获得翻页代码$sql="select * from news order by id desc limit ".$page->getlimitStartNum().",".$showNum;//查询新闻列表:获得从第几条开始$newsList=$dbMysql->getRowsArray($sql);foreach($newsList as $key=>$val){echo $val['id'],'--',$val['title'],"<br>\n";}echo $pageHtml;//输出翻页代码<?php/*** 翻页抽象类*/abstract class abstractPage{//protected $GP;// G/P:$_GET/$_POST.。
分页原理的最核心的内容是:把数据库中某一段的信息分段的显示在web页面上,实现这样的功能必须弄清楚以下1.分段显示在不同的页面上,那么页面如何确定呢?要解决这个问题主要是明白url的结构,使用parse_url()函数可以解析URL地址得到有固定键值的数组。
实际上,在url中,可以使用hostname/path?page=value来确定上下页面,这样问题转化为如何取得page,即当前页面的值?我们可以使用$_GET['page']解决这个问题。
2.解决页面问题之后,剩下的核心问题是如何去分段?使用limit查询条件,可以把信息分段出来,关键是如何确定limit后面的2个变量的值,一个是offset初始值,一个是pagesize,每页要显示多少内容。
假如当前页的值为page,那么offset=(page-1)*pagesize,例如:select*from`message`limit10,5表示的是显示第11-15个信息,共显示5个,当前页为第3页,(3-1)*5=10。
3.使用$_SERVER[REQUEST_URL]可以取得当前URL的除去hostname的部分,当点击下一页或上一页的时候,实际上又载入了一次页面,那么当前URL就会保留上一个页面的URL信息导致URL有问题,无法实现分页功能,因此,必须取得当前URL之后,使用URL解析函数,取得path部分,才能保证URL不会被更新。
4.链接数据库以及取得数据库信息的方法不再赘述。
只提供可能使用到的函数以供复习。
mysql_connect()die()mysql_error() mysql_select_db()mysql_query()mysql_fetch_array()mysql_num_rows()以下是一个简单的分页代码(只实现了共?条?页和上一页下一页功能):<?php$conn=@mysql_connect("localhost","root","123456")or die("数据库链接错误".mysql_error());mysql_select_db("test",$conn);mysql_query("set names'GBK'");//使用GBK中文编码;$pagesize=5;$numq=mysql_query("SELECT*FROM`message`"); $num=mysql_num_rows($numq);//取得信息总数if($num>$pagesize){if($num%$pagesize){$numpage=(int)($num/$pagesize)+1;}else{$numpage=$num/$pagesize;}}else{$numpage=1;}//计算一共有多少页的信息$url=$_SERVER[REQUEST_URI];$url=parse_url($url);$url=$url[path];//取得不会被更新的URL地址的path部分if(isset($_GET['page'])){$page=intval($_GET['page']);}//取得当前页page的值if($page<=0){$page=1;}//防止page为负数,数据库无法取得信息而报错。