I'm writing an online math testing program, and currently working on the scripts to calculate the rank that each user got. The following code works, but I cringe every time I see it.
get_set() puts the result of the query into $users
function rank_users_in_test($tid){
$GLOBALS['DB']->get_set($users,"select user,test from user_results where test=$tid order by points desc,time");
// $users are already in order by rank thanks to ORDER BY
$rank = 1;
foreach ($users as $u){
$GLOBALS['DB']->query("update user_results set world_rank=$rank where user={$u['user']} and test={$u['test']}");
$rank++;
}
}
The query in the loop makes me cry a bit. My question is, is there a way that MySQL can automatically update each user's rank based on the order they appeared in the result on the first query? There is a related question here, but it does not use UPDATE.
I'm using MySQL 5.