Reputation: 570
I have a hash database on my own site, and I wanted to paginate (because 210.000hashes won't load easily without slowing down the site)
now I have paginated my stuff, but I get about 21.000 pages how can I limit this to about 100pages???
$sql = "SELECT * FROM hashes";
$rs_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='?page=".$i."'>".$i."</a> ";
};
echo "<a href='?page=$total_pages'>".'>|'."</a> "; // Goto last page
Please don't mind the crappy way I made it, I just want it to work, not look pretty :)
Upvotes: 0
Views: 1015
Reputation: 570
This piece of code made it work for me :) (the '5' pieces still gotta be editted with the $max_pages
$max_pages = 10;
$rs_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i = max(1, $page - 5); $i <= min($page + 5, $total_pages); $i++) {
echo "<a href='?page=".$i."'>".$i."</a> ";
};
echo "<a href='?page=$total_pages'>".'>|'."</a> "; // Goto last page
Upvotes: 0
Reputation: 1681
Pagination in php
Limit the number of items per page by
if(isset($_GET['page']))
$page=$_GET['page'];
else
$page=1;
$max_results=6;
$from=( ($page * $max_results) - $max_results);
in this i limit 6(
$max_results=6;
) items per page you can change according to your needUse the query to limit the results
$search=mysql_query("SELECT * FROM `hashes` LIMIT $from,$max_results");
$total_results=mysql_result(mysql_query("select count(*) as num from `hashes`"),0);
while($r=mysql_fetch_object($search))
{//your code}
Pagination concept to provide links for pages
$total_pages=ceil($total_results/$max_results);
if($total_results>$max_results)
{
if($page>1)
{
$prev=($page-1);
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$prev\" style='text-decoration:none'> << Previous </a>";
}
for($i=1;$i<=$total_pages;$i++)
{
if($page==$i)
{
echo $i."";
}
else
{
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\" style='text-decoration:none'> $i </a>";
}
}
if($page<$total_pages)
{
$next=($page+1);
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$next\" style='text-decoration:none'> Next>></a>";
}
}
Upvotes: 2
Reputation: 620
Consider using LIMIT clause in sql query - it will be efficient and will solve your problem
Upvotes: 0