Log in

View Full Version : Resolved Showing nearest 5 results of for() loop?



MrEvil
11-12-2008, 08:14 PM
Would that be possible?

I have this:

$viewpage = $_GET['viewpage'];
$records_per_page = 14;
$offset = ($viewpage-1) * $records_per_page;
$id = is_numeric($_GET['id']);

$count_result = mysql_query("SELECT COUNT(*) FROM entries WHERE tid='$id'"); // $id is the post ID displayed in the URL
$count_row = mysql_fetch_array($count_result);
$count = $count_row["COUNT(*)"];
for($i=1; $i<=$count/$records_per_page; $i++){
$i2 = $i+1; //wait for it...
echo '<a class="page" href="?id='.$_GET["id"].'&amp;viewpage='.$i.'">'.$i.'</a>';
} echo '<a class="page" href="?id='.$_GET["id"].'&amp;viewpage='.$i2.'">'.$i2.'</a>'; //one page is always missing

What that does is create page links, and splits MySQL results across multiple pages. It works fine, but having 100 links at the bottom of the page can be pretty cluttered. Is there a way so it displays the closest 5 numbers?

For example, if you were on page 10:
[10]|[11]|[12]|[13]|[14]|[15]
...And so on. I've tried tinkering with a few if() statements and messing with the math parts, but to no success. Any ideas?

Woohoo. Thanks.

Twey
11-13-2008, 02:55 PM
$margin = 2;

for ($i = $viewpage - $margin;
$i <= $count / $records_per_page && $i <= $viewpage + $margin;
++$i)
...

MrEvil
11-13-2008, 04:05 PM
You.Are.Awesome. That works perfectly. The only thing I did was change || to &&, so it displays the page numbers before and after the current one (which is even better than what I originally wanted). Thank you soooo much. :D

Twey
11-14-2008, 04:03 AM
Oh yes, of course. Silly me. Sorry.