【问题标题】:How to use PHP to sum SQL data如何使用 PHP 对 SQL 数据求和
【发布时间】:2015-05-06 20:49:59
【问题描述】:

我想为我的论坛创建一个“toplist”类型的东西。我有一个电脑游戏的杀戮日志。所以在我的 sql 表“受害者”中,我有几行数据。我想用 $killforumid 来为整个表求和 $score 。有多个具有相同 $killforumid 的条目,我想对其进行排序并为该用户添加分数。

看起来像这样:

User 1 = 1000 points, 60 kills
User 2 = 5000 points, 100 kills

PHP 代码:

$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT score, killforumid FROM hcvictims";
$result = $conn->query($sql);

【问题讨论】:

  • 如果不是查询中的所有计算,您也可以完成大部分计算
  • 您想使用聚合函数。所以SELECT sum(score), killforumid FROM hcvictims GROUP BY killforumid ORDER BY sum(score) DESC
  • 对...但是我如何用 killforumid - score 回应它们

标签: php mysql sql sum add


【解决方案1】:

如果您使用RightClick 查询(我会建议):

$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT sum(score), killforumid FROM hcvictims GROUP BY killforumid ORDER BY sum(score) DESC";
$result = $conn->query($sql); 
while($row = $result->fetch_row())
{
    echo "killforumid: " . $row[1] . ", score : " . $row[0] . "\n"; 
}
/* free result set */
$result->free();

见:mysqli-result object, fetch-row method

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多