This question already has an answer here:
I will do a project for my database class (new in databases). I will use php. The tables are created in mysql. I have to display a webpage with some information:
attr1 | atrr2 | atrr3 | atrr4
| | |
| | |
But I want to display the last inserted 20 rows. Then, if the user wants to see the other rows inserted, the webpage will have a next page button showing the following 20 rows (not the same ones).
I know that I can use something like:
select (attributes) from tbl ORDER BY 'ID' DESC LIMIT 20
1- But then, How I can retrieve (with php programming) the other 20 rows? If I use the same query it will display the same information.
2- I was thinking to just query all the data and somehow store it, but I don't know if it is a good choice to store all the data even if the user does not want to see it. I want to do it as my first question because I have to retrieve other information from other tables in the database.
What do you suggest? And how I can retrieve the data as I want in my first question?
</div>
I made one of these recently in a project. I used the Bootstrap pagination class to style it:
<div class="pagination" style="text-align:center">
<ul>
<?php
if($firstPage)
{
$relative = "./";
}
else
$relative = "../";
if($page != 1)
{
echo "<li><a href=\"".$relative."page/$page\">«</a></li>";
}
for($i = 1; $i <= ceil($numRows / $numItems); $i++)
{
if($i == $page)
echo "\t<li><a href=\"".$relative."page/$i"."\" style=\"background-color:#e5e5e5;color:#AAAAAA;\"><b>".$i."</b></a></li>";
else
echo "\t<li><a href=\"".$relative."page/$i\">".$i."</a></li>";
}
if(($page+1) <= ceil($numRows / $numItems))
echo "\t<li><a href=\"".$relative."page/".($page+1)."\">»</a></li>";
?>
</ul>
</div>
Then in the controller, I form the query:
$numItems = 20; // Number of results to show per page
$q = "SELECT * FROM --- WHERE ---- = $-----";
$q .= " LIMIT ".(($page_number-1)*$numItems).','.($numItems*($page_number));
This concept is called pagination
. In this -
1st) LIMIT 20,0 (from 1 to 20)
2nd) LIMT 20,20 (from 21 to 40)
3rd) LIMIT 20,40 (from 41 to 60)
4th) LIMIT 20,60 (from 61 to 80)
It is a combination of limit
and offset
. 1st, 2nd, 3rd... are the page and the (LIMIT 20,0) are the addons to the query, and offset
parameter you'll get from $_GET
(from URL
)