Maggi Iggam
Maggi Iggam

Reputation: 692

How to effeciently print names in database sorting according to a coloumn in php/mysql?

More precisely . I have a table say 'data' , which has many coloumns out which 2 are : 'Name' & 'Score' being Text and Integer type respectively. Now without editing the actual table itself , i just need to print all the Names in decreasing order of Scores . I guess O(N^2) should work too as there are hardly 1000 entries . I am using php/mysql.

Upvotes: 0

Views: 32

Answers (2)

paddyfields
paddyfields

Reputation: 1539

Query:

 SELECT name, score FROM data ORDER BY score DESC

PHP (mysqli). Assuming $db is your database connection:

$stmt = $db->prepare("SELECT name, score FROM data ORDER BY score DESC");
$stmt->execute;
$result = $stmt->get_result;
$stmt->close();

while($row = $result->fetch_assoc()){
  echo $row['name'];
  echo ": ";
  echo $row ['score'];
  echo "</br>";
}

Upvotes: 1

Fjarlaegur
Fjarlaegur

Reputation: 1443

I dont know if this is exactly what you are looking for, but as far as i understand you just need the right MySQL query?

SELECT name, score FROM data ORDER BY score DESC

This would select all the names and their respective scores in descending order.

Then you just need to loop through it in a php file, printing them out on the page in whatever style suits you.

I hope it helps.

Cheers.

Upvotes: 1

Related Questions