基于一个特定字段对php表进行排序

时间:2012-01-06 05:09:28

标签: php gridview-sorting

您好我正在尝试根据$ fratio对此表进行排序。拥有最高$ fratio的人将被列为表中的第1位。这是我到目前为止所使用的代码 -

// MySQL connection.
$connection = mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database. Be sure the databasename exists and online is.");
$query="SELECT `UserID`,`Playername`,`Kills`,`Deaths` FROM users LIMIT 0,50"; 
$query = mysql_query($query);

echo('<table width="300" border="2" cellspacing="3" cellpadding="3">
<tr>
    <td style="min-width:150px;">Playername:</td>
    <td style="width:100px">Kills:</td>
    <td style="width:100px">Deaths:</td>
    <td style="width:100px">Ratio:</td>
</tr>');
while($row = mysql_fetch_assoc($query))
{
$id = $row['UserID'];
$playername = $row['Playername'];
$kills = $row['Kills'];
$deaths = $row['Deaths'];
$ratio = ($kills/$deaths);
$fratio = ceil($ratio); 

echo('
  <tr>
    <td style="min-width:150px;"><a href="stats.php?id='.$id.'">'.$playername.'</a></td>
    <td style="width:100px">'.$kills.'</td>
    <td style="width:100px">'.$deaths.'</td>
    <td style="width:100px">'.$fratio.'</td>
  </tr>');
  }
  echo('</table>');

  mysql_close($connection);
  ?>

2 个答案:

答案 0 :(得分:2)

您可以尝试使用

ORDER BY kills / deaths DESC

所以完整的查询看起来像

SELECT `UserID`,`Playername`,`Kills`,`Deaths` FROM users ORDER BY kills / deaths DESC LIMIT 0,50

完整代码如下所示:

// MySQL connection.
$connection = mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database. Be sure the databasename exists and online is.");
$query="SELECT `UserID`,`Playername`,`Kills`,`Deaths` FROM users ORDER BY kills / deaths LIMIT 0,50"; 
$query = mysql_query($query);

echo('<table width="300" border="2" cellspacing="3" cellpadding="3">
<tr>
    <td style="min-width:150px;">Playername:</td>
    <td style="width:100px">Kills:</td>
    <td style="width:100px">Deaths:</td>
    <td style="width:100px">Ratio:</td>
</tr>');
while($row = mysql_fetch_assoc($query))
{
$id = $row['UserID'];
$playername = $row['Playername'];
$kills = $row['Kills'];
$deaths = $row['Deaths'];
$ratio = ($kills/$deaths);
$fratio = ceil($ratio); 

echo('
  <tr>
    <td style="min-width:150px;"><a href="stats.php?id='.$id.'">'.$playername.'</a></td>
    <td style="width:100px">'.$kills.'</td>
    <td style="width:100px">'.$deaths.'</td>
    <td style="width:100px">'.$fratio.'</td>
  </tr>');
  }
  echo('</table>');

  mysql_close($connection);
  ?>

以下是“ORDER BY”的示例。你应该考虑阅读至少这个以获得它的主要想法。

http://www.w3schools.com/php/php_mysql_order_by.asp

答案 1 :(得分:0)

你将在mysql中使用比例:

ORDER BY CEILING( kills / deaths ) DESC