Ahmad Ahmad - 6 months ago 27
PHP Question

how to use paging in displaying records from the database?

I am displaying some records from the database. Currently I am displaying the top twenty records but I want to show all records with twenty records per page.

How will I use the paging in php to display all records?'

Any Idea about this?


Something like this might work:

$posts_per_page = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
$query = sprintf("SELECT * FROM <table> LIMIT %d, %d", 
                  $page * $post_per_page, 
$result = mysql_query($query);

The above query will select 10 records with a offset based on the current page. You will also have to get the total number of pages based on the $posts_per_page:

$query = "SELECT COUNT(*) c FROM <table>";

You will have to keep track of the total number of posts divided with $posts_per_page and also the current page, then you can display a prev and next link:

if ($current_page > 0) {
   echo '<a href="index.php?page=' . ($current_page - 1) . '>prev</a>';
if ($current_page < $max_pages - 1) {
   echo '<a href="index.php?page=' . ($current_page + 1) . '>next</a>';