Prashant Ingale

Juice of PHP, MySQL, Apache, Linux, Actionscript, Flex

Archive for September 1st, 2008

How to display results on multiple pages using pagination : PHP MySQL

leave a comment

Paging means showing long result in multiple pages. If sql query returns 1000 rows then page will take much time to load the page. It will burn bandwidth as well. By splitting result in multiple pages you can save time as well you don’t have to do much scrolling.

To show the result of a query in several pages first you need to know how many rows you have and how many rows per page you want to show. For example if I have 295 rows and I show 30 rows per page that mean I’ll have ten pages (rounded up).

For the example I created a table named randoms that store 295 random numbers. Each page shows 20 numbers.

// 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;

$query  = “SELECT val FROM randoms LIMIT $offset, $rowsPerPage”;

$result = mysql_query($query) or die(’Error, query failed’);

// print the random numbers

while($row = mysql_fetch_array($result))

{

	echo $row['val'] . ‘‘;

}

echo ‘‘;

// how many rows we have in database

$query   = “SELECT COUNT(val) AS numrows FROM randoms”;

$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;

Written by admin

September 1st, 2008 at 2:41 am

Posted in PHP