Search code examples
phpnumberssequenceranking

PHP sequential numbering


I'm having trouble with my page here:

LINK

My "rank" part of the table keeps resetting back to zero when you click on page 2 and beyond. It doesn't start at 21, it just resets back to zero.

How do I fix that?

<?php 
include ("database.php");
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 
$start_from = ($page-1) * 20; 
$sql = ("SELECT * FROM voting ORDER BY votepoints DESC LIMIT $start_from, 20") or die ("Error 1."); 
$rs_result = mysql_query ($sql) or die (include ("error.html"));
$rank = 1;
?> 
<table>
<tr><td>Rank</td><td></td><td>Username</td><td></td><td></td><td></td><td>Vote points</td></tr>
<?php
while ($row = mysql_fetch_assoc($rs_result)) { 
?> 
            <tr>
            <td><? echo $rank++; ?></td>
            <td></td>
            <td><? echo $row["username"]; ?></td>
            <td></td>
            <td></td>
            <td></td>
            <td><? echo $row["votepoints"]; ?></td>
            </tr>
<?php 

}; 
?> 
</table>


<?php
echo '<br>';
echo 'Total Votes: ';
include ("sum.php");
include("database.php");

$sql = "SELECT COUNT(votepoints) FROM voting"; 
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 20);

echo '<span class="text-bleumarin">';
if($page>1)
$pagelink ='<a href="votes.php?page='.($page-1).'">prev</a> ';
echo $pagelink;

for ($i=1; $i<=$total_pages; $i++) {
if ($i != $page)
echo "<a href='votes.php?page=".$i."'>".$i."</a> ";
if ($i==$page)
echo '' . $i . ' ';
};


if($page<$total_pages)
$pagelink ='<a href="votes.php?page='.($page+1).'">next</a> ';
echo $pagelink;
echo '</span>';

?>

Solution

  • EDIT: this is the line you need to change *EDIT2: subtracted 1 from page as you set 1 to default.*

    <td><? echo (($page-1)*20)+$rank++; ?></td>
    

    This will do:

    (0*20) + 1 = 1
    (0*20) + 2 = 2
    ...
    (0*20) + 20 = 20
    (1*20) + 1 = 21
    (1*20) + 2 = 22
    ...
    (1*20) + 20 = 40
    (2*20) + 1 = 41
    (2*20) + 2 = 42
    ...
    (2*20) + 20 = 60
    ...
    (21*20) + 1 = 421
    

    Note: No code provided when this solution was posted

    Assuming you are using a for loop of some sort to keep count:

    if (!isset($_GET['page']))
    {
        $page=0;
    }
    else
    {
        $page=$_GET['page'];
    }
    for($i=1; $i<21; $i++)
    {
        echo '<tr>';
        echo '<td>'.($page*20)+$i.'</td>;' //THIS IS THE RANK LINE
        //Other fields
        echo '</tr>';
    }