PHP获取所有行的值

时间:2015-09-23 12:37:57

标签: php mysql count

我的“用户”表格中有列money,我需要PHP来计算所有用户拥有的总金额。

我知道这会计算行但我不知道如何用PHP获得游戏中的总金额

<?php
$r = $sql->query("SELECT * FROM `users` WHERE `health`='100' AND `level`='1'");
$user = mysql_fetch_object($r);
echo"There are:<br>";
echo mysql_num_rows($r);
echo" Users in the database<br>";
echo"Total there are:<br>";
echo number_format($user->money); //I want it to calculate how much money there are inn the game but i cant find a way to do this
echo" Money inn the game<br>";
?>

我知道我应该选择MYSQLI或PDO但我稍后会开始使用它。

2 个答案:

答案 0 :(得分:3)

为什么不用以下方式查询数据库:

SELECT SUM(`money`) FROM `users` WHERE `health`='100' AND `level`='1'

答案 1 :(得分:3)

您可以使用SUM()。在这种情况下,MySQL将使用隐式GROUP BY,因此您不需要指定它。这将为您提供游戏中的用户数和总金额:

SELECT COUNT(*) AS num_users, SUM(money) AS total_money 
 FROM `users` 
 WHERE `health`='100' AND `level`='1';

要将其转换为PHP,您应该能够:

<?php
$r = $sql->query("SELECT COUNT(*) AS num_users, SUM(money) AS total_money FROM `users` WHERE `health`='100' AND `level`='1';");
$user = mysql_fetch_object($r);
echo"There are:<br>";
echo $user->num_users;
echo" Users in the database<br>";
echo"Total there are:<br>";
echo number_format($user->total_money); //I want it to calculate how much money there are inn the game but i cant find a way to do this
echo" Money inn the game<br>";
?>