Jump to content

Adding Numbers To Each Result - Can't figure it out!


sandbox

Recommended Posts

Hi,

 

I'm new to the forums and would like to take this opportunity to say hello to everybody. :)

 

I'm having a slight problem and was wondering if you kind folks could shed some light on it for me please. Basically, I am trying to add numbers, ascending from 1 to 50, to the left side of each persons username. The person with the highest gold amount would have 1. next to their name, then 2. for the second highest, and so forth. I'm thinking a for or foreach loop is the answer, but I cannot seem to get it right.

 

$sql = "SELECT * FROM `users` ORDER BY `gold` DESC LIMIT 50";

$qry = mysql_query($sql);

while ($res = mysql_fetch_array($qry)) {

     echo $res['username'] . " "; 
     echo $res['gold'] . "<br /><br />";
}

 

 

Thanks for your time.

Hey,

 

Welcome to the club! You joined a great community!

 

If you want to make this really easy, instead of using a foreach loop, just echo and ordered list <ol></ol>. So something like this......

echo "<ol>";
echo "<li>" . $res['username'] . "";
echo $res['gold'] . "<br/><br/>" . </li>;
echo "</ol>"

 

I am not really sure how you want to arrange your content, but that would be the start.

  On 4/3/2013 at 10:18 AM, sandbox said:

 

Hi,

 

I'm new to the forums and would like to take this opportunity to say hello to everybody. :)

 

I'm having a slight problem and was wondering if you kind folks could shed some light on it for me please. Basically, I am trying to add numbers, ascending from 1 to 50, to the left side of each persons username. The person with the highest gold amount would have 1. next to their name, then 2. for the second highest, and so forth. I'm thinking a for or foreach loop is the answer, but I cannot seem to get it right.

 

$sql = "SELECT * FROM `users` ORDER BY `gold` DESC LIMIT 50";

$qry = mysql_query($sql);

while ($res = mysql_fetch_array($qry)) {

     echo $res['username'] . " "; 
     echo $res['gold'] . "<br /><br />";
}

 

 

Thanks for your time.

 

 

If you do want to use a loop, initialise a counter before the loop starts and then increment it before the bottom of the loop:

$sql = "SELECT * FROM `users` ORDER BY `gold` DESC LIMIT 50";
$qry = mysql_query($sql);
$counter = 1; // create a counter before the loop starts
while ($res = mysql_fetch_array($qry)) {
    echo $counter . " " . $res['username'] . " " . $res['gold'] . "<br />";
    $counter++; // add 1 to counter for each iteration of loop
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.