Ranking PHP and SQL, without repeating database record

Asked

Viewed 72 times

-2

I’m developing a ranking with php and sql, I can list the data correctly. However, I need to make sure that no repeated records appear.

My code:

<?php
    include_once('conexao.php');
    $rank = "SELECT * FROM ranking ORDER BY pontuacao DESC LIMIT 0, 6";
    $query = mysqli_query($mysqli, $rank);
    $i = 0;
    if(($query) AND ($query->num_rows != 0)){
      while($row = mysqli_fetch_assoc($query)){

         $id_usuario = $row['id_usuario'];
         $pontos = $row['pontuacao'];
      }
    }
?>


<html>
<body>
<div style="background: lightgray;width: 120px;height: 40px; margin-bottom: 20px; padding: 30px;">

          <h5><?php echo "id_usuario: ".$id_usuario." "."<br>pontos: ".$pontos; ?></h5> 
</div>
</body>
</html>

<?php 

} else {
    echo "nem um registro encontrado!";    
}

inserir a descrição da imagem aqui

  • edit and improve your question. Put your code better tbm

2 answers

0

It would be simpler to bring the desired values to the database, avoiding having to make unnecessary loops in your PHP code, so you save time loading the page and make your code easier to maintain. Something like that should solve your problem:

$rank = "SELECT id_usuario, MAX(pontuacao) AS 'pontuacao_maxima' FROM ranking GROUP BY id_usuario";

Also change the part that prints the data, it should be in the body of the page. The way you put it, your code will always print the last result, and that is not the desired behavior.

while($row = mysqli_fetch_assoc($query)){
    echo "id_usuario: ". $row['id_usuario'] . " fez ". $row['pontuacao_maxima'] . " pontos";
}

-1

I suggest you do it this way, take the php block with the structure while and put inside the html, getting like this:

<html>
<body>
<div style="background: lightgray;width: 120px;height: 40px; margin-bottom: 20px; padding: 30px;">
    <?php
        include_once('conexao.php');
        $rank = "SELECT * FROM ranking ORDER BY pontuacao DESC LIMIT 0, 6";
        $query = mysqli_query($mysqli, $rank);
        $i = 0;
        if(($query) AND ($query->num_rows != 0)){
          while($row = mysqli_fetch_assoc($query)){

             $id_usuario = $row['id_usuario'];
             $pontos = $row['pontuacao'];

             echo "id_usuario: ".$id_usuario." "."<br>pontos: ".$pontos;
          }
        } else {
          echo "nem um registro encontrado!";    
        }
    ?> 

</div>
</body>
</html>

NOTE: I have not tested, try it. If you do not solve anything, come and comment on the problem.

Browser other questions tagged

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