How to rank with PHP

Asked

Viewed 3,424 times

4

Well, I have a problem, I know how to pull the ranking and all.

My question is I’m gonna pull the 6 with the highest score, and I wanted the first 3 to have a different background, like:

Whatever comes first: yellow;

The second place: blue;

The third place: red;

The rest: gray;


How can I do that?

Code:

<?php
$rank = mysql_query("SELECT * FROM forum ORDER BY pontos DESC LIMIT 6") or die(mysql_error()); ?> 
 <?php $i = 0; while($row = mysql_fetch_assoc($rank)){ $i++; ?>
<div style="background: gray;width: 60px;height: 20px;padding: 20px;">
<?php echo $row['username']; ?> com <?php echo $row['pontos']; ?>
</div>
<?php } ?>
  • It would be a ranking of what exactly, @Kloves?

  • Users with more posts.

1 answer

8


Elaborate as follows:

<?
    #Pontuação
    function coresPts($posicao){

        switch($posicao){

            case 0: 
                $cor = "#FFCC00";
                break;

            case 1:
                $cor = "#000000";
                break;

            case 2:
                $cor = "#CCCCCCC";
                break;

        }

        return $cor;

    }

# Buscando pontuação
$rank = mysql_query("SELECT * FROM forum ORDER BY pontos DESC LIMIT 0, 6") or die(mysql_error());

    $i = 0;
    while($row = mysql_fetch_assoc($rank)){
        $i++; 
?>
<div style="background: <? echo coresPts($i); ?>;width: 60px;height: 20px;padding: 20px;">
    <?php echo $row['username']; ?> com <?php echo $row['pontos']; ?>
</div>
<? } ?>

Explanation: We create a function called coresPts that will seek the score according to the increment of $i. And then we return the correct color for each of the positions, just you change the $cor of each position. The position 0 would be the first position, 1 the second position and 2 the third position.

  • I changed, it was incorrect switch(), his variable put another, sorry. Now you’re right.

  • It worked @kloves?

  • Gave yes, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.