user3813511
user3813511

Reputation: 39

Php number each query result

I am making a leaderboard, I want to number it like 1st place 2nd place etc in a html table field.

How to I number each row of information coming out? Something like $result + 1 ?

My query

$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 1");

                            while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];

}

Thanks.

Upvotes: 0

Views: 65

Answers (2)

fortune
fortune

Reputation: 3372

With query itself you can build the result, I think this is what u needed. Not sure

SELECT    @curRank := @curRank + 1 AS rank, a.*
FROM      playerdata a, (SELECT @curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900

In php

$result = mysqli_query($con,"SELECT    @curRank := @curRank + 1 AS rank, a.*
    FROM      playerdata a, (SELECT @curRank := 0) r
    WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");

while($row = mysqli_fetch_array($result)) {
    $rank = $row['rank'];
    $bank = $row['Bank'];
}

Upvotes: 0

Bailey Herbert
Bailey Herbert

Reputation: 410

You can sort through the query results using:

$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$rows = mysqli_num_rows($result);

for($x = 1; $x <= $rows; $x++) {
    $row = mysqli_fetch_array($result);
    echo "#{$x} " . $row['bank'];
}

This will start counting down, showing "#1... #2... #3..." etc. You can also do this with your while loop:

$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");

$x = 1;
while($row = mysqli_fetch_array($result)) {
    $bank = $row['bank'];
    echo "#{$x} " . $bank;
    $x++;
}

Upvotes: 2

Related Questions