用PHP MySQL進(jìn)行分頁的詳細(xì)說明(一)
Jun 08, 2016 pm 05:33 PM分頁顯示詳解
1、前言
分頁顯示是一種非經(jīng)常見的瀏覽和顯示大量數(shù)據(jù)的方法,屬于web編程中最常處理的事件之一。對(duì)于web編程的老手來說,編寫這種代碼實(shí)在是和呼吸一樣自然,但是對(duì)于初學(xué)者來說,經(jīng)常對(duì)這個(gè)問題摸不著頭緒,因此特地撰寫此文對(duì)這個(gè)問題進(jìn)行具體的講解,力求讓看完這篇文章的朋友在看完以后對(duì)于分頁顯示的原理和實(shí)現(xiàn)方法有所了解。本文適合初學(xué)者閱讀,所有示例代碼均使用php編寫。
2、原理
所謂分頁顯示,也就是將數(shù)據(jù)庫中的結(jié)果集人為的分成一段一段的來顯示,這里需要兩個(gè)初始的參數(shù):
每頁多少條記錄($PageSize)?
當(dāng)前是第幾頁($CurrentPageID)?
現(xiàn)在只要再給我一個(gè)結(jié)果集,我就可以顯示某段特定的結(jié)果出來。
至于其他的參數(shù),比如:上一頁($PreviousPageID)、下一頁($NextPageID)、總頁數(shù)($numPages)等等,都可以根據(jù)前邊這幾個(gè)東西得到。
以mysql數(shù)據(jù)庫為例,假如要從表內(nèi)截取某段內(nèi)容,sql語句可以用:select * from table limit offset, rows??纯聪旅嬉唤Msql語句,嘗試一下發(fā)現(xiàn)其中的規(guī)率。
前10條記錄:select * from table limit 0,10
第11至20條記錄:select * from table limit 10,10
第21至30條記錄:select * from table limit 20,10
……
這一組sql語句其實(shí)就是當(dāng)$PageSize=10的時(shí)候取表內(nèi)每一頁數(shù)據(jù)的sql語句,我們可以總結(jié)出這樣一個(gè)模板:
select * from table limit ($CurrentPageID - 1) * $PageSize, $PageSize
拿這個(gè)模板代入對(duì)應(yīng)的值和上邊那一組sql語句對(duì)照一下看看是不是那么回事。搞定了最重要的如何獲取數(shù)據(jù)的問題以后,剩下的就僅僅是傳遞參數(shù),構(gòu)造合適的sql語句然后使用php從數(shù)據(jù)庫內(nèi)獲取數(shù)據(jù)并顯示了。以下我將用具體代碼加以說明。
3、簡單代碼
請(qǐng)具體閱讀以下代碼,自己調(diào)試運(yùn)行一次,最好把它修改一次,加上自己的功能,比如搜索等等。
// 建立數(shù)據(jù)庫連接
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("Could not connect: " . mysql_error());
// 獲取當(dāng)前頁數(shù)
if( isset($_GET['page']) ){
$page = intval( $_GET['page'] );
}
else{
$page = 1;
}
// 每頁數(shù)量
$PageSize = 10;
// 獲取總數(shù)據(jù)量
$sql = "select count(*) as amount from table";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$amount = $row['amount'];
// 記算總共有多少頁
if( $amount ){
if( $amount
if( $amount % $page_size ){ //取總數(shù)據(jù)量除以每頁數(shù)的余數(shù)
$page_count = (int)($amount / $page_size) 1; //假如有余數(shù),則頁數(shù)等于總數(shù)據(jù)量除以每頁數(shù)的結(jié)果取整再加一
}else{
$page_count = $amount / $page_size; //假如沒有余數(shù),則頁數(shù)等于總數(shù)據(jù)量除以每頁數(shù)的結(jié)果
}

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To add MySQL's bin directory to the system PATH, it needs to be configured according to the different operating systems. 1. Windows system: Find the bin folder in the MySQL installation directory (the default path is usually C:\ProgramFiles\MySQL\MySQLServerX.X\bin), right-click "This Computer" → "Properties" → "Advanced System Settings" → "Environment Variables", select Path in "System Variables" and edit it, add the MySQLbin path, save it and restart the command prompt and enter mysql--version verification; 2.macOS and Linux systems: Bash users edit ~/.bashrc or ~/.bash_

The key steps for installing MySQL on Windows 11 are as follows: 1. Download the correct version, select the Windows MSI installation package and ensure that the system is 64-bit; 2. Select the "Custom" mode during installation, add MySQLServer and set the appropriate installation path; 3. Run the configuration wizard, select the "ServerComputer" configuration type, set the root password, and select the automatic startup method; 4. After the test installation is successful, if the prompt command is unavailable, add the MySQL bin directory to the system PATH environment variable. Follow these steps to complete the installation and configuration smoothly.

To reset the root password of MySQL, please follow the following steps: 1. Stop the MySQL server, use sudosystemctlstopmysql or sudosystemctlstopmysqld; 2. Start MySQL in --skip-grant-tables mode, execute sudomysqld-skip-grant-tables&; 3. Log in to MySQL and execute the corresponding SQL command to modify the password according to the version, such as FLUSHPRIVILEGES;ALTERUSER'root'@'localhost'IDENTIFIEDBY'your_new

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

Turn on MySQL slow query logs and analyze locationable performance issues. 1. Edit the configuration file or dynamically set slow_query_log and long_query_time; 2. The log contains key fields such as Query_time, Lock_time, Rows_examined to assist in judging efficiency bottlenecks; 3. Use mysqldumpslow or pt-query-digest tools to efficiently analyze logs; 4. Optimization suggestions include adding indexes, avoiding SELECT*, splitting complex queries, etc. For example, adding an index to user_id can significantly reduce the number of scanned rows and improve query efficiency.

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

TosecurelyconnecttoaremoteMySQLserver,useSSHtunneling,configureMySQLforremoteaccess,setfirewallrules,andconsiderSSLencryption.First,establishanSSHtunnelwithssh-L3307:localhost:3306user@remote-server-Nandconnectviamysql-h127.0.0.1-P3307.Second,editMyS

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.
