Home > Backend Development > PHP Tutorial > 用php制作简单分页(从数据库读取记录)的方法详解_PHP

用php制作简单分页(从数据库读取记录)的方法详解_PHP

WBOY
Release: 2016-06-01 12:06:56
Original
1377 people have browsed it

      PHP新手,一直想做一下分页都给忘了,今天有幸被提醒所以网上搜了一下。有些写的看不懂也没怎么去看。最后找到一个比较简单的。

  大致的思想就是:

  1.设置每页要显示的最大记录数。

  2.计算出页面总数

  3.当前页面跟总页面数比较改变连接的状态

  4.用limit控制从数据库中读取记录

下面是代码:
复制代码 代码如下:
$conn = mysql_connect('localhost','root','');
            mysql_select_db('db_BookStore',$conn);
            mysql_query("set names utf8");
            if(isset($_GET['page']))                   //判断是否存在page参数,获得页面值,否则取1
            {
                $page = intval($_GET['page']);
            }
            else
            {
                $page = 1;
            }
            $page_size = 2; //最大记录条数
            $sql = "SELECT count(*) as amount FROM tb_BookInfo";
            $result = mysql_query($sql);
            $row = mysql_fetch_array($result);
            //计算总页数
            $amount = $row['amount'];
            if($amount)
            {
                if($amount                 if($amount % $page_size){$page_count = (int)($amount / $page_size) + 1; }
                else{$page_count = $amount / $page_size;}
            }
            else
            {
                $page_count = 0;
            }
            //翻页链接
            $page_string = "";
            if($page == 1)
            {
                $page_string .= "首页 | 上一页";
            }
            else
            {
                $page_string .= "首页 | 上一页";
            }
            $page_string .= "| $page |";
            if($page == $page_count)
            {
                $page_string .= "下一页 | 尾页";
            }
            else
            {
                $page_string .= "下一页 | 尾页";
            }
          $sql = "select * from table order by id desc limit ". ($page-1)*$page_size .", $page_size";
          $result = mysql_query($sql);
       while ( $row = mysql_fetch_row($result) ){
         $rowset[] = $row;
       }
?>

这个只是非常简单的一种方法,各位路人大牛,若有其他类型的方法,敬请告之一下。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template