Dom
Dom

Reputation: 3126

Score board php loop

I am fairly new to php so probably my question will sound simple for many, but here is my issue.

I have a table in MySQL holding scoreboard for users.

$connection = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");

function score_table() {
    global $sql;

    if ($sql) {
        $rows_num = mysql_num_rows($sql);
        while ($row = mysql_fetch_array($sql)) {
            for ($i = 0; $i <= $rows_num; $i++) {
                echo $i;
            }
            echo $i.$row['name']." ".$row['score']."<br />\n";
        }
    }
}

the result im getting is :

123456Player1 3
123456Player2 400
123456Player3 784
123456Player4 1500
123456Player5 1642

So there is 5 players. Although firstly $i has 6 results and it is going through the entire loop for each player.

What i am trying to achieve is this:

1Player1 3
2Player2 400
3Player3 784
4Player4 1500
5Player5 1642

where first number is simply position. So whoever has less points is on the first place.

Upvotes: 0

Views: 270

Answers (1)

samura
samura

Reputation: 4395

$connection = mysql_connect('localhost' ,'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");

function score_table()
{
  global $sql;
  $i=1;

  if($sql)
  {
    while($row = mysql_fetch_array($sql)) 
    {
      echo $i++ . $row['name'] . " " . $row['score'] . "<br />".PHP_EOL;
    }
  }
}

Upvotes: 1

Related Questions