Friday, June 19, 2009

How to paging using php mysql

1. Setup how many rows to show per page
// how many rows to show per page
$rowsPerPage = 20;

// by default we show first page
$pageNum = 1;

// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

2. Set your query

$tbl_name="record"; // Table name

$sql="SELECT * FROM $tbl_name LIMIT $offset, $rowsPerPage";
$result=mysql_query($sql);

3. Display the result
while($rows=mysql_fetch_array($result)) {

echo $rows['id'];
echo $rows['name'];

}
?>

4. Display how many rows we have in database and page

// how many rows we have in database
$query = "SELECT COUNT(id) AS numrows FROM $tbl_name";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav = '';

for($page = 1; $page <= $maxPage; $page++)
{
if ($page == $pageNum)
{
$nav .= " $page "; // no need to create a link to current page
}
else
{
$nav .= " $page ";
}
}
// creating previous and next link
// plus the link to go straight to
// the first and last page

if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " [Prev] ";

$first = " [First Page] ";
}
else
{
$prev = ' '; // we're on page one, don't print previous link
$first = ' '; // nor the first page link
}

if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " [Next] ";

$last = " [Last Page] ";
}
else
{
$next = ' '; // we're on the last page, don't print next link
$last = ' '; // nor the last page link
}

// print the navigation link
echo $first . $prev . $nav . $next . $last;
?>

Enjoy ubuntu... ;)

No comments:

kunkun-laptop .... ;)