phprockers-logo

Pagination in php

When we have a large list of items, we can display them grouped in pages and presents navigational elements to move from one page to another. This code creates a pagination for listing the page per 10 records.

<?php

$con = mysql_connect('localhost','ramakrishnan','raman') or die(mysql_error()); ;
mysql_select_db('rama_db',$con) or die(mysql_error()); ;

$page = $_REQUEST['page'];
if($page == "" || $page == null ) {
    $page = 1;
} else {
    $page = $page;
}

//setting the limit for fetching the records.
$per_page_limit = 10;
if($page >1) {
    $start_limit = ($page-1)*$per_page_limit;
    } else {
    $start_limit = 0;
}


//getting the records by limits
$query = "SELECT id, name, qualification FROM emplouee WHERE salary > 10000 ORDER by salary LIMIT " .$start_limit. ','.$per_page_limit;
$results=mysql_query($query);
print_r($results);
$num_rows = mysql_num_rows($results);
while($row=mysql_fetch_array($results))
{
    echo "<div class = 'emp_id'>";
    echo $row['id'];
    echo "</div>";
    echo "<div class = 'emp_name'>";
    echo $row['name'];
    echo "</div>";
    echo "<div class = 'emp_qualify'>";
    echo $row['qualification'];
    echo "</div>";
}
<!-- pagination for listing posts/articles-->

$myabsoluteurl = "http://" . $_SERVER['HTTP_HOST']."/your foldername";

if($num_rows > 0)
{
$start=1;
$prev = $page - 1;                            //previous page is page - 1
$next = $page + 1;
$total_page=ceil($$num_rows/$per_page_limit);
$lastpage=$total_page;


if($total_page > 1) {
    echo "<div class='pagination'>"; 
    //start page
    if($page == 1)
    echo "<span>«« Start</span>".' ';
    else
    echo '<a href="'.$url.$start.'" >«« Start</a>'.' ';

    //previous page
    if ($page > 1) 
    echo '<a href="'.$url.$prev.'" >« Previous</a>'.' ';
          else
    echo "<span>« Previous</span>".' ';

    for($i=1; $i<=$total_page; $i++) {
        if($i == $page)
        echo "<span>[".$i."]</span>";
        else
        echo '<a href="'.$url.$i.'">['.$i.']</a>'.' ';
    }


    if ($page < $lastpage) 
    echo '<a href="'.$url.$next.'" >Next » </a>'. ' ';
    else
    echo "<span>Next » </span>".' ';


    //last page start
    if($page != $total_page)
    echo '<a href="'.$url.$lastpage.'">Last »» </a>'.' ';
    else
    echo "<span>Last »» </span>".' ';
    //last page end
    echo "</div>";
}
}
?>

0 comments:

Post a Comment