PHP, MYSQLI implementation pagination (beginners)
/ / the idea of implementing paging for the first time (of course, it's someone else's idea, I just wrote it down)
/ / 1. Find out the total number of items if 13
/ / prepare the sql statement (query the total number of data from the database bbs_ user table) $sql = "select count (*) as count from bbs_user"; / / send the sql statement (number of received queries) $result = mysqli_query ($conn,$sql); / / process the result set $pageRes = mysqli_fetch_assoc ($result); / / var_dump ($pageRes) / / $count takes the number of entries out of the result set (total number of entries) $count = $pageRes ['count']
Var_dump ($count); take a look:
/ / 2. Requirements: only 5 items are displayed per page
$num = 5
/ / 3. Ceil (total number of entries / number of displays per page) ceil is rounded up, even if there is one left, it will occupy a separate page (3 pages)
$pageCount = ceil ($count / $num); / / number of pages
Var_dump ($pageCount); print to check:
/ / 4. Calculate the offset according to the total number of pages (that is, which article will start at the beginning of the next page, the formula derived below)
$offset = ($page-1) * $sum (5)
/ / 5. $page can be set to a default value of 1, but there is no value yet, so we can give an initial value
$page = 1
/ / 6. Modify the sql statement (this sql is not the other sql statement) and use the limit restriction (derivation below)
$sql = "select * from bbs_user limit". $offect. ','. $num; / / where limit must be followed by a space, otherwise there will be an error
/ / you can run it to see what effect it has.
/ / 7. Haven't we written the first page, the next page, the home page and the last page yet?
Home page, previous page, next page, last page
/ / 8. Modify the initial value of $page, and we automatically get the value of page
$page = $_ GET ['page']
/ / at this point we will find that something has gone wrong! Empty? How to change it?
/ / our initial goal is to get the initial value of $page to be 1, so we can add a conditional judgment. If it's empty, it's 1, otherwise it's the number of pages.
$page = empty ($_ GET ['page'])? 1: $_ GET [' page']; / / trinocular operation
/ / 9. Let's first give the link to the front page and the last page (simple), and then write down the previous page and the next page.
/ / the home page is the main page, namely page=1
Home page
/ / the last page is the total number of pages (as you can imagine, the total number of pages is the last page)