Forum Moderators: coopster

Message Too Old, No Replies

Sorting and put ranking No. in field using PHP and MYSQL database

         

Rachit

8:17 pm on Apr 27, 2005 (gmt 0)

10+ Year Member



I have 3 field in my MYSQL table Ranking, Name and Score.

Is it possible to sort all record to order by Score and put Ranking no. to each record by using query not much?
If it possible how to do it?

Sorry for my english.

jatar_k

8:48 pm on Apr 27, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld Rachit,

no worries about your english, I understood just fine.

You don't really need to order them in the table but you can easily order them on select. Something like

select * from mytable order by ranking desc

this query would give you all of your results in order highest to lowest score. Then you could use a loop to output them and use a counter to put their rank beside them.

or is it necessary to put the rank in the table?

mcibor

8:54 pm on Apr 27, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome Rachit to WebmasterWorld!

The ranking would be done better by simple php:

<?php
$ask = "SELECT name, score FROM table ORDER BY score DESC;//desc means that the highest is the first. You can add LIMIT 20 - only first 20 will be shown.
$conn = mysql_connect("dbhost", "dblogin", "dbpassword") or die(mysql_error());
mysql_select_db("dbname", $conn) or die(mysql_error());
$query = mysql_query($ask, $conn) or die(mysql_error());
if(mysql_num_rows($query)) {
$rank = 0;
$old_score = "";
while($answer = mysql_fetch_array($query, MYSQL_BOTH))//so you can write $answer[0] and $answer['name'] {
if(($score = $answer['score']) == $old_score) echo $rank." exequo";
else echo ++$rank;
echo ", .$answer['name'].", $score<br>";//it should be done in tds, but you'll manage
$old_score = $score;
}}
?>

Best regards
Michal Cibor

Rachit

2:28 am on Apr 28, 2005 (gmt 0)

10+ Year Member



Thankyou for answer.
I want to put ranking No. back to table that will made ton of query because i must update every record to put ranking no.

How i can optimize this process?

jatar_k

4:42 pm on Apr 28, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I think a cron would be the best, you could do it every night maybe.

create a column for ranking
select the ordered results into an array
loop through the array and issue an update query for each row that will insert the proper rank.