我有玩家的分数被添加到表格中,我想在PHP中检查他们的分数是否在前10名之内或者在前10名之外。
我有以下内容,现在需要添加查询以对highscore
中的DESC
进行排序,并让我知道userid
是否排在前10位。
电流:
$currentuser = $_SESSION['userid'];
$mysqli = new mysqli($hostname, $db_username, $db_password,$db_name);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$res = $mysqli->query("SELECT * FROM players WHERE userid=" . $currentuser);
尝试:
$currentuser = $_SESSION['userid'];
$mysqli = new mysqli($hostname, $db_username, $db_password,$db_name);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$current = $mysqli->query("SELECT * FROM players WHERE userid=" . $currentuser);
$res = $mysqli->query("SELECT * FROM players ORDER BY highscore DESC LIMIT 10");
foreach ($res as $player) {
if ($player = $current) {
echo "in the top 10" }
else {
echo "not in the top 10"}
}
这是正确的,检查$currentuser
是否在前10名中是否正确,或者是否能以更清洁的方式实现?
答案 0 :(得分:1)
假设您要列出所有用户,然后表示哪些用户位于前10名,那么这里有一个选项可以将整个列表组合成一个查询,使用子查询获得前10名玩家,{{{ 1}}语句和case
:
outer join
鉴于您的意见,这可能是最简单的选择:
select p.userid,
case
when p2.userid is not null
then 'in the top 10'
else 'not in the top 10'
end intopten
from players p
left join (select *
from players
order by highscore desc
limit 10) p2 on p.userid = p2.userid
答案 1 :(得分:0)
您可以使用以下查询:
$query="SELECT 1 from players WHERE $currentuser in (SELECT userid FROM players ORDER BY highscore DESC LIMIT 10) LIMIT 1"
if($result=$mysqli->query($query))
{
if($result->num_rows >0 )echo 'in top 10';
else echo 'not in top 10';
}
else echo 'error';