PHP Paging principle + page code + pagination class production

Source: Internet
Author: User

Pagination display is a very common way to browse and display large amounts of data, which is one of the most frequently handled events in Web programming. For the veteran of Web programming, writing this code is just as natural as breathing, but for beginners, there is often no clue to the problem, so write this article specifically to explain the problem in detail.

first, the principle of paging:
The so-called paging display, that is, the result set in the database is artificially divided into a section of the display, here requires two initial parameters:

How many records per page ($PageSize)?
What is the current page ($CurrentPageID)?

Now just give me a result set and I can show a specific result.

For other parameters, such as the previous page ($PReviousPageID), the next page ($NextPageID), the total number of pages ($numPages), and so on, can be based on the front of these things.

For example, in MySQL database, if you want to intercept a piece of content from within a table, the SQL statement can be used: SELECT * FROM table limit offset, rows. Take a look at the following set of SQL statements and try to find out the rate of compliance.

Top 10 Records: SELECT * FROM table limit 0,10
11th to 20th record: SELECT * FROM table limit 10,10
21st to 30th Record: SELECT * FROM table limit 20,10
......
This set of SQL statements is actually a SQL statement that takes every page of data in the table when $pagesize=10, and we can summarize a template like this:
SELECT * FROM table limit ($CurrentPageID-1) * $PageSize, $PageSize
Take this template and replace the corresponding value with the set of SQL statements above to see if that's the case. Take care of the most important question of how to get the data, all that is left is to pass the parameters, construct the appropriate SQL statement, and then use PHP to retrieve the data from the database and display it.


Two, paging code Description: Five Steps

The code is fully explained and can be copied to your own Notepad directly using

  1. <meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
  2. <title> Employee Information List </title>
  3. <?php
  4. Display information for all EMP tables
  5. 1. Connect to the database
  6. $conn =mysql_connect (' localhost ', ' root ', ' 1234abcd ') or Die (' Connection Database error '. mysql_error ());
  7. 2. Select a database
  8. mysql_select_db (' empmanage ');
  9. 3. Select a character Set
  10. mysql_query (' Set names UTF8 ');
  11. 4. Send SQL statements and get results for processing
  12. 4.1 Paging [paging to emit two SQL statements, one to get $rowcount, and one to get paged results through the limit of SQL. So we're going to get two result sets and remember to distinguish them when naming them.
  13. Paging (four values of two SQL statements). ]
  14. $pageSize =3;//How many records are displayed per page
  15. How many records are there in $rowCount =0;//?
  16. $pageNow =1;//want to display the first few pages
  17. $pageCount =0;//altogether have how many pages [pagination altogether this four indicators, is indispensable. Since $rowcount can be obtained from the server, it can be given an initial value of 0;
  18. $pageNow want to display the first few pages, it is best to set to 0, $pageSize is the number of records per page, which is based on the requirements of the site in advance.
  19. $pageCount =ceil ($rowCount/$pageSize), since $rowcount can have an initial value of 0, the $pagecount can of course be set to 0. Four indicators, two 0, one 1, and the other for website requirements. ]
  20. 4.15 Modify the value of the $pagenow according to the paging link
  21. if (!empty ($_get[' Pagenow ')) {
  22. $pageNow =$_get[' Pagenow '];
  23. }[modifies the value of $pagenow according to the paging link. ]
  24. $sql = ' SELECT count (ID) from EMP ';
  25. $res 1=mysql_query ($sql);
  26. 4.11 Number of rows removed
  27. if ($row =mysql_fetch_row ($res 1)) {
  28. $rowCount = $row [0];
  29. }//[get $rowcount,, into the We will know $pagecount these two indicators. ]
  30. 4.12 Calculate the total number of pages
  31. $pageCount =ceil ($rowCount/$pageSize);
  32. $pageStart = ($pageNow-1) * $pageSize;
  33. 4.13 Sending SQL results with paging
  34. $sql = "SELECT * from emp limit $pageStart, $pageSize";//[paging is implemented based on the two values (starting value, per page number) following the limit of the $sql statement. And the two values are evaluated. ]
  35. $res 2=mysql_query ($sql, $conn) or die (' cannot get result set '. Mysql_error ());
  36. Echo ' <table border=1> '; [echo "<table border= ' 1px ' cellspacing= ' 0px ' bordercolor= ' red ' width= ' 600px ' >";]
  37. "<tr><th>id</th><th>name</th><th>grade</th><th>email</th ><th>salary</th><th><a href= ' # ' > Delete user </a></th><th><a href= ' # ' >        Modify User </a></th></tr> "; while ($row =mysql_fetch_assoc ($res 2)) {
  38. echo "<tr><td>{$row [' id ']}</td><td>{$row [' name ']}</td><td>{$row [' Grade ']} </td><td>{$row [' email ']}</td><td>{$row [' Salary ']}</td><td><a href= ' # '        > Delete User </a></td><td><a href= ' # ' > Modify User </a></td></tr> "; }
  39. Echo ' </table> ';
  40. 4.14 Print out a hyperlink to a page number
  41. for ($i =1; $i <= $pageCount; $i + +) {
  42. echo "<a href= '? pagenow= $i ' > $i </a>"//[print out the page number of hyperlinks]
  43. }
  44. 5. Release the resource, close the connection
  45. Mysql_free_result ($res 2);
  46. Mysql_close ($conn);
  47. ?>
Copy Code


Third, simple paging class sharing

Now publish a simple sorting production. As long as you understand the principles and procedures of this class, other complex classes can be comprehend by analogy. No nonsense, directly on the source, you can directly use in your project.

Database Operation Class Code: mysqli.func.php

  1. <?php
  2. Database Connection Constants
  3. Define (' db_host ', ' localhost ');
  4. Define (' Db_user ', ' root ');
  5. Define (' db_pwd ', ');
  6. Define (' Db_name ', ' guest ');
  7. Connecting to a database
  8. Function Conn ()
  9. {
  10. $conn = Mysqli_connect (Db_host, Db_user, Db_pwd, db_name);
  11. Mysqli_query ($conn, "Set names UTF8");
  12. return $conn;
  13. }
  14. Get the result set
  15. function Doresult ($sql) {
  16. $result =mysqli_query (Conn (), $sql);
  17. return $result;
  18. }
  19. Result set to object collection
  20. function Dolists ($result) {
  21. Return Mysqli_fetch_array ($result, MYSQL_ASSOC);
  22. }
  23. function Totalnums ($sql) {
  24. $result =mysqli_query (Conn (), $sql);
  25. return $result->num_rows;
  26. }
  27. Close the database
  28. function Closedb ()
  29. {
  30. if (! Mysqli_close ()) {
  31. Exit (' close exception ');
  32. }
  33. }
  34. ?>
Copy Code

Pagination Implementation code:

What's hidden in this post
  1. <?php
  2. Include ' mysqli.func.php ';
  3. Total Record Count
  4. $sql = "Select dg_id from Tb_user";
  5. $totalnums = Totalnums ($sql);
  6. Show number of bars per page
  7. $fnum = 8;
  8. Number of pages
  9. $pagenum = Ceil ($totalnums/$fnum);
  10. Page Constants
  11. @ $tmp = $_get[' page '];
  12. Prevent malicious paging
  13. if ($tmp > $pagenum)
  14. echo "<script>window.location.href= ' index.php ' </script>";
  15. Calculate Paging Start value
  16. if ($tmp = = "") {
  17. $num = 0;
  18. } else {
  19. $num = ($tmp-1) * $FNUM;
  20. }
  21. Query statements
  22. $sql = "Select Dg_id,dg_username from Tb_user ORDER by dg_id DESC LIMIT". $num. ", $fnum";
  23. $result = Doresult ($sql);
  24. Traverse output
  25. while (!! $rows = dolists ($result)) {
  26. echo $rows [' dg_id ']. " " . $rows [' Dg_username ']. "<br>";
  27. }
  28. Page link
  29. for ($i = 0; $i < $pagenum; $i + +) {
  30. echo "<a href=index.php?page=". ($i + 1). ">". ($i + 1). "</a>";
  31. }
  32. ?>
Copy Code

PHP Paging principle + page code + pagination class production

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.