当前位置:   article > 正文

php mysql分页_使用PHP和Mysql分页

limit %d,%d

php mysql分页

Requirements

要求

PHP 5.3+

PHP 5.3以上

mysqli connection library

mysqli连接库

MySQL 5+

MySQL 5+

Introduction

介绍

This article gives an overview of how to add pagination to your application. If you have an application that has to display multiple rows of data it is advisable to break this information up into pages so as not to overwhelm the reader.

本文概述了如何向您的应用程序添加分页。 如果您的应用程序必须显示多行数据,则建议将此信息分成几页,以免使读者不知所措。

The Basics

基础

MySQL has a useful feature LIMIT which allows you to select how many rows you want to retrieve from a query and what row to start from. It is therefore easy to break your rows up into pages all you need is

MySQL具有一项有用的功能LIMIT ,它使您可以选择要从查询中检索多少行以及从哪一行开始。 因此,很容易将您的行分成几页,您所需要的只是

PageSize - specifying how many rows per page you are interested in

PageSize-指定您感兴趣的每页多少行

PageNumber - identifies a particular page

PageNumber-标识特定页面

TotalRows - how many rows there are in the dataset

TotalRows-数据集中有多少行

With the above information it is simple to build the queries to retreive the data you need

利用以上信息,可以轻松构建查询以检索所需的数据

The query to retrieve the data from the dataset would need to look something like this

从数据集中检索数据的查询需要看起来像这样

  1. SELECT field1, field2, ...
  2. FROM table
  3. WHERE condition
  4. LIMIT StartRow, TotalRows

All we need to do is calculate the value of [StartRow] and [TotalRows].

我们需要做的就是计算[StartRow]和[TotalRows]的值。

Where [StartRow] and [TotalRows] are calculated and added to your query by your script

通过脚本计算[StartRow]和[TotalRows]并将其添加到查询中的位置

StartRow

起始行

This is simply a product of the PageSize and the requested PageNo - 1.

这简直是每页和要求您做生意的产物- 1。

LIMIT works from a 0 base but people are more used to pages starting from 1 so we need to subtract 1 from the human readable page to get the start page for Limit

LIMIT从0的基础开始工作,但是人们更习惯于从1开始的页面,因此我们需要从人类可读的页面中减去1以获得Limit的开始页面

Example

If our PageSize = 10 and PageNumber is 3 then we calculate StartRow as

如果我们的PageSize = 10且PageNumber为3,则我们将StartRow计算为

StartRow = 10 x (3 -1) = 20

起始行= 10 x(3 -1)= 20

TotalRows is simply the PageSize which you can define as constant in your script OR add functionality for the user to select how many rows they want to see on a page.

TotalRows只是PageSize,您可以在脚本中将其定义为常量,或者添加功能以供用户选择他们希望在页面上看到多少行。

What is the Total number of Pages in the Recordset?

记录集中的总页数是多少?

N It would be useful to show the visitor how many pages there are in the table. How do we find the total number of rows that would have been retrieved had we not added LIMIT to the query?

N向访问者显示表中有多少页会很有用。 如果不将LIMIT添加到查询中,我们如何找到将要检索的总行数?

One way is to run another query with COUNT to return the number of available rows

一种方法是使用COUNT运行另一个查询以返回可用行数

SELECT COUNT(*) FROM table WHERE condition

SQL_CALC_FOUND_ROWS.

SQL_CALC_FOUND_ROWS

If we add SQL_CALC_FOUND_ROWS to our query MySQL will automatically store the total number of rows in the dataset. We can retrieve this value by calling the FOUND_ROWS() function in MySQL.

如果我们向查询中添加SQL_CALC_FOUND_ROWS ,MySQL将自动在数据集中存储总行数。 我们可以通过在MySQL中调用FOUND_ROWS()函数来检索此值。

Example

  1. SELECT SQL_CALC_FOUND_ROWS, field1, field2, ...
  2. FROM table
  3. WHERE condition
  4. LIMIT 20,10
SELECT FOUND_ROWS()

Putting it all together

放在一起

The code below is a fully functional pagination example. Before we can use it though we need to create the data.

下面的代码是一个功能齐全的分页示例。 在使用它之前,我们需要创建数据。

Client Table

客户表

  1. CREATE TABLE `client` (
  2. `id` int(11) NOT NULL auto_increment,
  3. `firstname` varchar(50) default NULL,
  4. `surname` varchar(50) default NULL,
  5. `email` varchar(50) default NULL,
  6. PRIMARY KEY (`id`)
  7. )

The Database class is a wrapper for the mysqli connection library

Database类是mysqli连接库的包装器

database.php

database.php

  1. // Our connection variables - in a real project these would most likely be
  2. // included in a config file that would be included in the application
  3. // deprecating the requirement to include them here.
  4. // They are reproduced here for clarity.
  5. define('db_server','localhost');
  6. define('db_user','user');
  7. define('db_password','password');
  8. define('db_database','ee');
  9. class Database
  10. {
  11. private $connection; // A property to hold our database connection
  12. function __construct()
  13. {
  14. $this->connection = new mysqli(
  15. db_server,
  16. db_user,
  17. db_password,
  18. db_database);
  19. }
  20. // A static method to return the current database connection
  21. // The function ensures a single instance of the database
  22. // object is used in the application
  23. static function &getConnection()
  24. {
  25. static $connection;
  26. // If a database object has not been instantiated then do so
  27. if (!is_object($connection)) {
  28. $connection = new Database();
  29. }
  30. return $connection;
  31. }
  32. // Wrapper function for the query method
  33. // This can be expanded with additional parameters to
  34. // use prepared statements etc
  35. function query($query)
  36. {
  37. return $this->connection->query($query);
  38. }
  39. }

Result class manages the results we retrieve from the database and renders the client table and pagination

Result类管理从数据库中检索到的结果,并呈现客户端表和分页

results.php

results.php

  1. // The pg_pagesize constant determines how many results you want
  2. // to see on a page. Again, this could be defined in the config file.
  3. // In more advanced implementations this can be modifiable by the
  4. // reader to show more or less items on a page.
  5. define('pg_pagesize', 10);
  6. class Results
  7. {
  8. private $pagenumber = null; // Requested page number
  9. private $result = null; // Results from querying the client table
  10. private $db = null; // Instance of the Database singleton class
  11. private $total = 0; // Total number of records in the client table
  12. // The constructor takes a requested pagenumber
  13. // It builds and executes the query against the client's table
  14. // It also calculates total number of rows in the client's table
  15. function __construct($pagenumber)
  16. {
  17. // We want to work with pagenumbers starting from 0 - but humans
  18. // are used to page numbers starting from 1 so we need to compensate.
  19. $this->pagenumber = $pagenumber - 1;
  20. // Store the pagenumber in the session so we don't annoy users
  21. // who navigate away from the page and want to see the same
  22. // results when they return
  23. $_SESSION['pagenumber'] = $this->pagenumber;
  24. // Calculate the start row
  25. $start = pg_pagesize * $this->pagenumber;
  26. // Build the query to fetch the required rows from the database
  27. // starting from the requested page
  28. $this->db = Database::getConnection();
  29. $query = sprintf("SELECT SQL_CALC_FOUND_ROWS * FROM `client` LIMIT %d, %d",
  30. $start, pg_pagesize);
  31. $this->result = $this->db->query($query);
  32. // Fetch the calculated total rows of the dataset without the LIMIT
  33. $total = $this->db->query("SELECT FOUND_ROWS() AS total");
  34. $row = $total->fetch_object();
  35. $this->total = $row->total;
  36. }
  37. // This is the workhorse of the class. It cycles through the dataset
  38. // and outputs the HTML rows for our data table
  39. function showResults()
  40. {
  41. print "<table>" . _L;
  42. print "\t<tr>" . _L;
  43. print "\t\t<th>First Name</th><th>Surname</th><th>Email</th>" . _L;
  44. print "\t</tr>" . _L;
  45. while($row = $this->result->fetch_object()) {
  46. print "\t\t<tr>" . _L;
  47. printf("\t\t\t<td>%s</td><td>%s</td><td>%s</td>" . _L,
  48. $row->firstname, $row->surname, $row->email);
  49. print "\t\t</tr>" . _L;
  50. }
  51. print "</table>" . _L;
  52. $this->result->close();
  53. }
  54. // Here is where the pagination happens.
  55. // The class is designed that this function can be called from
  56. // anywhere in the code (and multiple times)
  57. // It is not dependent on showResults having already been called.
  58. function showPagination()
  59. {
  60. // Calculate how many pages there are. We do that by taking the
  61. // integer division of the total rows
  62. $pages = intval($this->total / pg_pagesize);
  63. // and adding 1 if there is a reminder.
  64. $pages += ($this->total%$pages)?1:0;
  65. // Finally we have enough information to output our pagination HTML
  66. print "<div class=\"page-navigation\">" . _L;
  67. print '<a href="client.php?page=1" class="pagination-arrows">&lt;&lt;</a>';
  68. // We don't want to show the goto previous record if we are on record 1
  69. if ($this->pagenumber > 0) {
  70. printf( "<a href=\"client.php?page=%d\" class=\"pagination-arrows\">&lt;</a>",
  71. $this->pagenumber);
  72. }
  73. for($i=1;$i<=$pages;$i++) {
  74. if ($i == $this->pagenumber+1) {
  75. printf("<span>%d</span>" . _L, $i);
  76. }
  77. else {
  78. printf("<a href=\"client.php?page=%d\">%d</a>" . _L, $i, $i);
  79. }
  80. }
  81. // We don't want to show goto next record if we are on the last page.
  82. if ($this->pagenumber < $pages-1) {
  83. printf("<a href=\"client.php?page=%d\" class=\"pagination-arrows\">&gt;</a>",
  84. $this->pagenumber + 2);
  85. }
  86. printf("<a href=\"client.php?page=%d\" class=\"pagination-arrows\">&gt;&gt;</a>",
  87. $pages);
  88. print "</div>" . _L;
  89. }
  90. }

client.php

client.php

  1. // We are using sessions to store our pagenumber so initiate a session
  2. session_start();
  3. // shortcut to the newline character
  4. define('_L', PHP_EOL);
  5. // Include our workhorse files
  6. require_once('database.php');
  7. require_once('results.php');
  8. // Work out what page number to use
  9. // First we look to see if a page number is specified in the URL request.
  10. // If it is we sanitize it to remove everything except numbers.
  11. // If no page was found then default to the empty string
  12. $pageno = isset($_GET['page'])
  13. ? preg_replace('/[^0-9]/', '', $_GET['page'])
  14. : '';
  15. // This could have been done on one line but has been split for clarity
  16. // If pageno is empty then attempt to get it from the session.
  17. // If the session is not set yet then default to 1.
  18. $pageno = empty($pageno)
  19. ? (
  20. isset($_SESSION['pagenumber'])
  21. ? $_SESSION['pagenumber'] + 1
  22. : 1
  23. )
  24. : $pageno;
  25. // Instantiate the results object to output to the page
  26. $results = new Results($pageno);
  27. ?>
  28. <!doctype html>
  29. <html>
  30. <head>
  31. <title>Client Results Page</title>
  32. </script>
  33. <style type="text/css">
  34. body {
  35. font-size: 100%;
  36. font-family: Arial;
  37. }
  38. table {
  39. border-collapse: collapse;
  40. font-size: 0.8em;
  41. }
  42. th, td {
  43. border: 1px solid #888;
  44. padding: 2px 5px;
  45. }
  46. tr:nth-child(2n) {
  47. background: #effeff;
  48. }
  49. .page-navigation {
  50. font-size: 0.6em;
  51. }
  52. .page-navigation a.pagination-arrows {
  53. padding: 0 4px;
  54. }
  55. </style>
  56. </head>
  57. <body>
  58. <?php
  59. // Demonstrate that pagination can be output anywhere
  60. // and any number of times
  61. $results->showPagination();
  62. // Display our results
  63. $results->showResults(); ;?>
  64. // Demonstrate that pagination can be output anywhere
  65. // and any number of times
  66. $results->showPagination();
  67. ?>
  68. </body>
  69. </html>

SQL_CALC_FOUND_ROWS and FOUND_ROWS

SQL_CALC_FOUND_ROWSFOUND_ROWS

翻译自: https://www.experts-exchange.com/articles/12238/Pagination-with-PHP-and-Mysql.html

php mysql分页

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/139376
推荐阅读
相关标签
  

闽ICP备14008679号