2015-09-23 59 views
0

我在我的“用户”表中有money列,我需要PHP来计算所有用户拥有的总金额。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,但我会开始使用后来。

回答

3

为什么不查询数据库:

SELECT SUM(`money`) FROM `users` WHERE `health`='100' AND `level`='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>"; 
?>