2013-10-27 63 views
0

如何计算一段时间内的所有字段?例如:我有一段时间,那些有四行。每一行都有一个特定的数字。我想要的是,这些数字的总数是多少?连续计算所有字段

while ($row= mysql_fetch_assoc($select)) { 
echo $row['persons']; 
} 

人是为了多少人在一个组中。我希望这四行中的所有人都是这样。

$row['persons'](5) + 
$row['persons'](6) + 
$row['persons'](3) + 
$row['persons'](3) = 17 

(x)表示有多少人在现场。我如何计算这一段时间,所以我echo是:刚刚17

+1

你可以做这样的事情,直接用的mysql_query。使用mysql内部函数SUM()函数。 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum – Bernhard

回答

0

试试这个代码,请使用SUM函数

$result = mysql_query("SELECT SUM(persons) AS personCount FROM tableName"); 


if (!$result) { 
echo 'Could not run query: ' . mysql_error(); 
exit; 


} 


$row = mysql_fetch_row($result); 



echo $row[0]; 
1

很基本的问题,,如:

$total = 0 

while ($row= mysql_fetch_assoc($select)) { 

    $total += $row['persons']; 

} 

echo $total; 
+0

谢谢。但知道它回声四次。因为我有四行,我怎么能只回应最后一个? –

+0

你确定你的回声在@Cristian建议的循环之外吗? –

0

如果我得到你的权利,你要总结所有的数字在persons列。

$count = 0; 
while ($row= mysql_fetch_assoc($select)) { 
    $count += $row['persons']; 
} 
echo $count; 

虽然更好的方法是使用SUM()集合MySQL的内置函数。

+0

这个答案可能不是很有帮助。它与以前的100%相同,并且没有提供OP学习的新知识。 –