Using php to make a simple paging of to read records from the database

  • 2020-06-01 08:59:13
  • OfStack

PHP novice, 1 always wanted to do 1 pager was forgotten, today I was lucky to be reminded, so I searched for 1 on the Internet. Some of the writing did not understand and did not read much. Finally, I found an easy one.

The general idea is:

1. Set the maximum number of records to display per page.

2. Calculate the total number of pages

3. The current page changes the state of the connection compared with the total number of pages

4. Read records from the database with limit control

Here's the code:


$conn = mysql_connect('localhost','root','');
            mysql_select_db('db_BookStore',$conn);
            mysql_query("set names utf8");
            if(isset($_GET['page']))                   // To determine if there is page parameter , Gets the page value, otherwise takes 1
            {
                $page = intval($_GET['page']);
            }
            else
            {
                $page = 1;
            }
            $page_size = 2; // Maximum number of records 
            $sql = "SELECT count(*) as amount FROM tb_BookInfo";
            $result = mysql_query($sql);
            $row = mysql_fetch_array($result);
            // Total page count 
            $amount = $row['amount'];
            if($amount)
            {
                if($amount < $page_size){$page_count = 1;}
                if($amount % $page_size){$page_count = (int)($amount / $page_size) + 1; }
                else{$page_count = $amount / $page_size;}
            }
            else
            {
                $page_count = 0;
            }
            // Page link 
            $page_string = "";
            if($page == 1)
            {
                $page_string .= " Home page  |  on 1 page ";
            }
            else
            {
                $page_string .= "<a href='?page=1'> Home page </a> | <a href='?page=".($page-1)."'> on 1 page </a>";
            }
            $page_string .= "| $page |";
            if($page == $page_count)
            {
                $page_string .= " Under the 1 page  |  back ";
            }
            else
            {
                $page_string .= "<a href='?page=".($page+1)."'> Under the 1 page </a> | <a href='?page=$page_count'> back </a>";
            }
          $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;
       }
? > 

This is only a very simple method, you passers-by, if there are other types of methods, please let me know 1.


Related articles: