[英]Getting row position with multiple MySQL queries and PHP
我有一個如下的MySQL表:
id | player | game 1 | game 2 | game 3
--------------------------------------
1 | Joe | 345 | 34 | 64
2 | Mark | 12 | 256 | 35
3 | Dan | 156 | 134 | 122
該表有大約2萬個條目。 “游戲1”,“游戲2”,“游戲3”列包含每個游戲的玩家得分。
我需要為每個玩家創建一個頁面,在其中顯示他們在游戲1,游戲2,游戲3中的排名位置。全部放在一頁中。
首先,我不知道如何獲得用戶的排名位置……例如,如果我想輸出游戲1的喬的排名,我當然可以進行ORDERBY“游戲1”,但是我該如何然后得到喬的排名?
第二:是否可以在單個查詢中獲得喬1,游戲2和游戲3的排名,還是我必須做3個單獨的查詢?
謝謝您的幫助,非常感謝。
首先,您需要在其中放置一個ID列,該列會在每次添加播放器時自動遞增。 然后根據用戶的ID拉出該行。
使用PDO
//Set your user Id somehow.. Maybe from a session or from your URL
$userId = trim(strip_tags($_GET['userId']));
//Then query your db and order by game 1 descending from highest score down to 0
$user_sth = $dbh->prepare("SELECT player, game 1, game 2, game 3 FROM players ORDER BY game 1 DESC")
$user_sth->execute();
//start the rank at 1
$rank = 1;
//create a variable to store our results in
$results = '';
//fetch the result array
while($user = $user_sth->fetch(PDO::FETCH_ASSOC){
//maybe put it into a table row
$results .= '<tr><td>'.$rank.'</td><td>'.$user['player'].'</td><td>'.$user['game 1'].'</td></tr>';
//update our rank position number
$rank++;
}
現在您可以在$ html中的某處回顯$ results
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.