I am using PHP to insert data into a DB. I have a table called games and it's defined this way :
ID | Score | Rank
I want the rank column to be updated everytime a new row is added. Rank column have to sort Games by score.
For example :
ID | Score | Rank
1 | 5 | 2
2 | 9 | 1
When I add a new row (ID=3, Score=15) my table will be like this :
ID | Score | Rank
1 | 5 | 3
2 | 9 | 2
3 | 15 | 1
I have tried this in PHP but it dosen't seem to work :
try {
$bdd->exec("INSERT INTO games(score) VALUES('$score')");
} catch (Exception $e) {
die ($e->getMessage());
}
try {
$bdd->exec("UPDATE games set rank=(SELECT @curRank := @curRank + 1
AS rank FROM games g, (SELECT @curRank := 0) r
ORDER BY score;)");
} catch (Exception $e) {
die ($e->getMessage());
}
Any ideas how can this be done with PHP ? Or is there a way to set the column value by default to be the rank of the scores ?
try {
$bdd->exec("SET @pos := 0;
UPDATE games SET rank= ( SELECT @pos := @pos + 1 ) ORDER BY score DESC;)");
} catch (Exception $e) {
die ($e->getMessage());
}
This worked for me. Thanks anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.