I have hundreds of records in a database table.
$result = mysqli_query($con,"SELECT * FROM booking_tbl");
echo "<table border='1'>
<tr>
<th>Booking ID</th>
<th>Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['booking_nmbr'] . "</td>";
echo "<td>".$row['name_title']." ".$row['sender']."</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
It show all the records from the table booking_tbl
.
But I want to break the results 25 per page. How can I do that?
One easy way of doing this is by using the limit
and offset
keywords. limit
controls the number of rows to show, and offset
controls where the query starts. Obviously, they should be used together with the order by
clause.
So, e.g., for the first page you'd use:
SELECT * FROM booking_tbl ORDER BY booking_nmbr LIMIT 25 OFFSET 0
And for the second page:
SELECT * FROM booking_tbl ORDER BY booking_nmbr LIMIT 25 OFFSET 25
Easy. Just use the MySQL LIMIT
clause. So your code like this:
$result = mysqli_query($con,"SELECT * FROM booking_tbl");
Just set it to this:
$result = mysqli_query($con,"SELECT * FROM booking_tbl LIMIT 0,10");
That will set the query to get 10
records from an offset of 0
(meaning the first record).
The format is basically:
LIMIT offset, count
With offset
being the actual offset of the record set that you will retrieve. And count
being the record count.
So knowing that your next step is to set pagination by taking URL parameters and such to do something like this:
$offset = $_REQUEST['offset'];
$count= $_REQUEST['count'];
$result = mysqli_query($con,"SELECT * FROM booking_tbl LIMIT $offset,$count");
I consider that pseudo code since it will work, but you should really do filtering on the $_REQUEST
values, but the general concept is correct.
If you are interest to achieve this using Javascript then you can use javascript DataTable library. http://datatables.net/
You will get pagination,search and some other features within your table with a very simple method. Also, it is easy to implement and able to handle very large data.