Thursday, November 5, 2009

Pagination using PHP,Smarty And MySql

$sql="SELECT * FROM `fieldname1` WHERE is_active='Y' ORDER BY fieldmame2";
$rs=mysql_query($sql);
$num=mysql_num_rows($rs);
$i=0;
/*while ($row = mysql_fetch_array($rs)) {
$arr1[$j] = $row;
$j++;
}*/
////////////////////////////////////////////
if (!(isset($pagenum)))
{
$pagenum = 1;
}

//Here we count the number of results
//Edit $data to be your query

$rows = $num;

//This is the number of results displayed per page
$page_rows = 2;

//This tells us the page number of our last page
$last = ceil($rows/$page_rows);

//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}

//This sets the range to display in our query
$max = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;

$SqlQuery=$sql." LIMIT ". ($pagenum - 1) * $page_rows.",$page_rows";
$data_p=mysql_query($SqlQuery);

////////////////////////////////////////////
while($row1 = mysql_fetch_array($data_p)) {
$arr[$i] = $row1;
$i++;
}
if ($pagenum == 1)
{
}
else
{
$previous = $pagenum-1;
}
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;

}
$smarty->assign("arr",$arr);
$smarty->assign("pagenum",$pagenum);
$smarty->assign("previous",$previous);
$smarty->assign("last",$last);
$smarty->assign("next",$next);

2 comments:

Aritra said...

good job.

Suraj SIngh said...

Good job kajal but copy paste method is not good.
check this one
http://www.phpexpertsforum.com/pagination-in-smarty-using-php-and-mysql-t1505.html
who copied whose code i don't know....