Hello everyone,
I’m trying to work on next and previous buttons links but i run into problems
I want it to display the previous 2 and next 2 pages from the current page a visitor is currently visiting, but always display 5 pages in total (if there are 5 pages that is!)
so for example (bold is the currently visited page):
this is the easiest case to make:
2 pages from left and 2 pages from right of the current page
firstPage 1 2 3 4 5 lastPage
These are what doing trouble to me:
when some1 is on the first page or on the 2nd page… (this is how it should be shown)
firstPage 1 2 3 4 5 lastPage
firstPage 1 2 3 4 5 lastPage
when some1 is on last page or 1 before last… (this is how it should be shown)
firstPage 1 2 3 4 5 lastPage
firstPage 1 2 3 4 5 lastPage
Can some1 help me make a code in PHP that does that…? thanks…
Here is what i came up with, but whenever i fix 1 thing another problem pops-up and i guess there’s much cleaner code to do this…
...
$row = mysql_fetch_assoc(mysql_query("SELECT COUNT(ID) c FROM stats"));
$lastPage = ceil($row['c']/$rowsPerPage);
$phpself = $_SERVER['PHP_SELF'];
if ($lastPage != 1) // if there are any pages to display...
{
echo "<div id='buttons'>";
if ($pageNum==1) // if we are on the first page
{
echo "<strong>«</strong> <strong>1</strong>";
for($i=2;$i<=5 && $i<=$lastPage;$i++)
echo " <a href='$phpself?page=$i'>$i</a> ";
echo " <a href='$phpself?page=$lastPage'>»</a>";
}
else if ($pageNum < $lastPage) // if we are somewhere in the middle
{
$prev = $pageNum - 2;
$next = $pageNum + 2;
if($pageNum==2)
{
$prev = 1;
$next++;
}
if($pageNum==$lastPage-1)
{
$next = $lastPage;
if ($pageNum != 2)
$prev--;
}
echo "<a href='$phpself?page=1'>«</a> ";
for($i=$prev;$i<$pageNum;$i++)
echo " <a href='$phpself?page=$i'>$i</a> ";
echo " <strong>$i</strong> ";
for($i=$pageNum+1;$i<=$next;$i++)
echo " <a href='$phpself?page=$i'>$i</a> ";
echo " <a href='$phpself?page=$lastPage'>»</a>";
}
else // if we are on last page
{
$tmp = $lastPage - 4;
if($tmp < 1)
$tmp = 1;
echo "<a href='$phpself?page=1'>«</a>";
for($i=$tmp;$i<$lastPage;$i++)
echo " <a href='$phpself?page=$i'>$i</a> ";
echo "<strong>$lastPage</strong> <strong>»</strong>";
}
echo "</div>";
}