Introduction to the simple paging function of developing a simple news release system with PHP
Paging display is a very common method of browsing and displaying large amounts of data, and is one of the most commonly processed events in web programming.
The so-called paging display means that the result set in the database is artificially divided into sections for display. Two initial parameters are required here:
The number of news displayed on each page: $limitNews
Get the current number of pages: $page
Because the computer language defaults to starting from 0 to obtain records
If the number displayed per page is set to 3, $limitNews = 3,
Then the first page $page = 1 will display three records of 0, 1, 2
The second page $page = 2 will display three records of 3, 4, and 5
The third page $page = 3 will display three records of 6, 7, and 8
and so on. . . . . . . . .
Set a parameter $limitFrom from which piece of data to start reading
You can get it from the above rules:
$limitFrom = ($page - 1 ) * $limitNews;
will obtain data starting from the 0th, 3rd, and 6th items respectively.
Next we need to connect to the database and read the data
We still use the database name test and table name new:# created earlier ##
<?php $link = mysqli_connect('localhost','uesrname','password','test'); $sql = "select * from new"; // select * from表示獲取全部字段的值 $sqlCount = "select count(*) from new"; //count(*)統(tǒng)計的是結(jié)果集的總條數(shù) ?>
total number of news in the database table through query statements$countNews
<?php $retQuery = mysqli_query($link, $sqlCount); //查詢數(shù)量sql語句 $retCount = mysqli_fetch_array($retQuery); //獲取數(shù)量 $count = $retCount[0]?$retCount[0]:0; //判斷獲取的新聞數(shù)量 $countNews = $count; ?>
$countPage How many pages are displayed in total
<?php $countPage = $countNews%$limitNews; //求余數(shù)獲取分頁數(shù)量能否被除盡 if(($countPage) > 0) { //獲取的頁數(shù)有余 $countPage = ceil($countNews/$limitNews); // ceil() 函數(shù)向上舍入為最接近的整數(shù),除不盡則取整數(shù)+1頁, 10個新聞每個頁面顯示3個,成3個頁面,剩余1個單獨成1個頁面,這樣總共有4個頁面 } else { $countPage = $countNews/$limitNews; //如果是9個新聞每個頁面顯示3個,成3個頁面 } ?>
Previous page$prev, next page$next;
$prev = ($page - 1 <= 0 )?1:$page-1;
$next = ($page + 1 > $countPage)?$countPage:$page+1;
The page code is shown below:
<!DOCTYPE html> <html> <head> <meta charset=utf8"> <title>分表頁</title> </head> <body> <div> <a href="?page=<?php echo $prev;?>">|上一頁</a> <?php for($i=1; $i<=$countPage; $i++):?> <a href="?page=<?php echo $i;?>"><?php echo $i;?></a> <?php endfor;?> <a href="?page=<?php echo $next;?>">|下一頁</a> </div> </body> </html>Note: The above code uses a for loop to implement 1,2,3. . . . page effect.