繁体   English   中英

通过多个MySQL查询和PHP获取行位置

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM