Problem with ("select username, points from data order by points desc limit 10");

Asked

Viewed 106 times

0

I am trying to make a ranking system, where the username and the score appear. I am doing as follows:

$select = $mysqli->query("select username, pontos from data order by pontos desc limit 10");
  $row = $select->num_rows;
  $get = $select->fetch_array();
  $top_1 = $get[0];
  $top_1_pontos = $get[1];
  $top_2 = $get[2];
  $top_2_pontos = $get[3];

Using an echo on $top_1 it displays the user name with the highest score.

Using an echo on $top_1_pontos it displays the user’s score.

From the $top_1_pontos he exhibits nothing else... what I did wrong?

What is the correct way to get the ranking searching all users and listing the top 10?

Mysql looks something like this:

INSERT INTO `data` (`id`,`username`,`pontos`) VALUES 
(1,'Joao',9321),
(2,'Maria',151000),
(3,'Pedro',21201),
(4,'Jose',31252),
(5,'Antonio',131145),
(6,'Adriano',13211),
(7,'Marcelo',6897),
(8,'Juliana',53144);
  • How many records are in the table? You’ve tried print_r at $get to see everything it brings?

  • You are just selecting the username and the points in your query, that is $get[2] you no longer have anything. It should have been an error undefined index...

  • 1

    Hey, but then you asked to display only username and points, and nothing else... why didn’t you make a foreach() to list the records with the proper scores? You can paste your SQL here, and we set up a practical example

  • I edited with the data André, she is more or less that way.

1 answer

1


You need 1 fetch to read each record. So repeat fetch after displaying top_1 data. (and use indexes 0 and 1 again)

If you want to show all 10, it is more practical to place your fetch within the condition of a while.

EDIT: as you updated your question, I update my answer. Follow the code snippet in question:

while($get = $select->fetch_array()) {
  $nome = $get[0];
  $pontos = $get[1];
  //faz algo com $nome e $pontos
}

This will read the names and scores of the top 10.

  • 1

    The person responsible for the downvote could explain?

  • Cool, it worked out!

Browser other questions tagged

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