Php 添加MySQL值论坛专栏

Php 添加MySQL值论坛专栏,php,mysql,math,add,Php,Mysql,Math,Add,我想知道如何添加(使用PHP数学)从MySQL查询返回的所有值 $query = mysql_query("SELECT * FROM phpvms_pireps WHERE pilotid='$pilotcode'")or die(mysql_error()); 然后,对于它返回的每个结果,我希望它将距离列中的所有值相加;这些已经是数字格式 在PHP中将它们添加到一起后,回显总数 谢谢。您可以在MySQL中完成: SELECT SUM(distance) FROM phpvms_pireps

我想知道如何添加(使用PHP数学)从MySQL查询返回的所有值

$query = mysql_query("SELECT * FROM phpvms_pireps WHERE pilotid='$pilotcode'")or die(mysql_error());
然后,对于它返回的每个结果,我希望它将距离列中的所有值相加;这些已经是数字格式

在PHP中将它们添加到一起后,回显总数


谢谢。

您可以在MySQL中完成:

SELECT SUM(distance) FROM phpvms_pireps
当然,如果您还想选择其他值,这将不起作用。在这种情况下,您可以在fetch循环中执行此操作:

$distance = 0;
while ($row = mysql_fetch_assoc($query) {
    $distance += $row['distance'];
    /* more processing? */
}
echo $distance;


您的代码是QuerytoInjection,您使用的是不推荐使用的mysql扩展。使用PDO或mysqli切换到正确的参数化查询。

您可以在MySQL中进行:

SELECT SUM(distance) FROM phpvms_pireps
$total = 0;
while ($output = mysql_fetch_assoc($query)) {
  $total += $output['distance'];
}

echo $total;
当然,如果您还想选择其他值,这将不起作用。在这种情况下,您可以在fetch循环中执行此操作:

$distance = 0;
while ($row = mysql_fetch_assoc($query) {
    $distance += $row['distance'];
    /* more processing? */
}
echo $distance;

您的代码是QuerytoInjection,您使用的是不推荐使用的mysql扩展。使用PDO或mysqli切换到正确参数化的查询

$total = 0;
while ($output = mysql_fetch_assoc($query)) {
  $total += $output['distance'];
}

echo $total;
我希望这有帮助


我希望这能有所帮助。

为什么不直接使用
选择sum(phpvms\u pireps)作为总数
?哇,好久没看到phpvms了。你要开始VA,OP?你是不是正好在FSW上?为什么不直接使用
select sum(phpvms\u pireps)作为total
?哇,好久没看到phpvms了。你要开始VA,OP?你碰巧在FSW上吗?我想使用
$distance[]=$row['distance']
然后
$distance=array\u sum($distance)
更好。@你认为循环中的数组赋值加上额外的函数调用比简单的加法“更好”吗?怎么会这样呢?我认为使用
$distance[]=$row['distance']
然后
$distance=array\u sum($distance)
更好。@你认为循环中的数组赋值加上额外的函数调用比简单的加法“更好”吗?为什么呢