2015-09-23 82 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>"; 
?>