2

我有一个名为“member_points”的表,它的设置如下:

|----|-------|----------|------------------------|
| id |  uid  |  points  |  last_loggedin         |
|----|-------|----------|------------------------|
| 1  |  1    |  5075    |  2012-08-02 02:04:00   |
|----|-------|----------|------------------------|
| 2  |  2    |  2026    |  2012-08-04 02:15:02   |
|----|-------|----------|------------------------|

我在下面有一个功能。我希望函数根据“点”行中的数字回显或返回“排名#1”或“排名#2”等排名。

function getTopRanks($id) {  
   $sql = "SELECT MAX(points) AS toppoints FROM member_points";
   $r = mysql_query($sql);
   if ( $r !== false && mysql_num_rows($r) > 0 ) {
      while ( $a = mysql_fetch_assoc($r) ) {
          $points = stripslashes($a['toppoints']);
          return ''.$points.'';  
      }
   }
}

有人可以帮我实现吗?

4

3 回答 3

3

在您的 mysql 查询中使用 ORDER BY (http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html)

所以你的查询会变成

SELECT points FROM member_points ORDER BY points DESC

这将按点数对查询结果进行排序。(DESC 将使它们降序,而 ASC 将使结果升序)。

于 2012-08-04T18:46:44.170 回答
3

我认为您将根据积分对用户进行排名。对于此类问题,我建议您在DESC订单上对用户进行排名第一。然后从行中提取欲望值。

function getTopRanks($id) {

   $sql = "SELECT uid FROM member_points ORDER BY points DESC ";
   $r = mysql_query($sql);
   if ( $r !== false && mysql_num_rows($r) > 0 ) {
      while ( $a = mysql_fetch_assoc($r) ) {
         $points = stripslashes($a['toppoints']);

           return ''.$points.'';

     }
   }

 }

这将解决您的问题。:)

根据您的要求更新:

function getTopRanksUser($id) {
$userPos ="Ranked position is:";
  $count = 0;
  $sql = "SELECT uid FROM member_points ORDER BY points DESC ";
  $r = mysql_query($sql);
  if ( $r !== false && mysql_num_rows($r) > 0 ) {
    while ( $a = mysql_fetch_assoc($r) ) {
       $count = $count+1;
       $userPosCount = $userPos+$count;

       return $userPosCount;

  }
 }

}

应该有返回 userPos+count。因为计数增加了表中的行数,并且字符串排名位置始终保持不变。这将给出结果。您可以根据您的要求更改返回字符串。:) 谢谢。

于 2012-08-04T18:52:55.540 回答
0

这是我用于排名的内容......此代码还考虑了关系并正确显示。只需将“用户名”和“点”更改为数据库中适当的列名,然后设置数据库连接变量:$hostName $databaseNanme $username 和 $password 即可。

希望这可以帮助!

    $sql1 = "SET @rnk=0; SET @rank=0; SET @scount=0;";
    $sql2 = "SELECT username, points, rank FROM
    (
        SELECT AA.*,BB.username, points
        (@rnk:=@rnk+1) rnk,
        (@rank:=IF(@scount=points,@rank,@rnk)) rank,
        (@scount:=points) newscount
        FROM
        (
            SELECT * FROM
            (SELECT COUNT(1) scorecount,points
            FROM users GROUP BY points
        ) AAA
        ORDER BY points DESC
    ) AA LEFT JOIN users BB USING (points)) A;";

try {
    $conn = new PDO('mysql:host='.$hostName.';dbname='.$databaseName, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->query($sql1);
    $data = $conn->query($sql2);

    $standings = $data->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log( 'ERROR: ' . $e->getMessage() );
}

print_r($排名);

于 2013-09-12T18:48:35.363 回答