1

抱歉问了一个简单的问题。

我还是 php 新手,所以我还在学习。

例如使用while($row = mysql_fetch_assoc($sql)),我查询并回显了单个列名称“权重”,在 4 个结果之后,each $row['weight']其值为 30、15、20、35。如何获取这些值并执行加法以获得重量的总值。

<?php

  $sql = mysql_query("SELECT weight FROM table WHERE ID = '$ID'");

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

  echo $row['weight'];

  ?>

样本输出:

30
15
20
35

我想执行加法。

30+15+20+35=100

4

7 回答 7

4

为此,在 PHP 中只需将每个权重添加到$total循环内的变量中:

$sql = mysql_query("SELECT weight FROM table WHERE ID = '$ID'");
$total = 0;
while ($row = mysql_fetch_assoc($sql)){
    $total += $row['weight'];
}
echo $total;

但是,您可能还想考虑直接在 sql 中执行此操作:

$sql = mysql_query("SELECT SUM(weight) AS total FROM table WHERE ID = '$ID'");
$row = mysql_fetch_assoc($sql);
$total = $row['total'];

另请注意,mysql从 PHP 5.5 开始不推荐使用函数,并且将来会被删除,您需要查看mysqli_queryorPDO::query代替。

于 2013-04-30T02:23:26.430 回答
3

你让mysql为你计算:

SELECT SUM(weight) AS total FROM table WHERE ID = '$ID' GROUP BY ID;

例子:

  $sql = sprintf(
      'SELECT SUM(weight) AS total FROM table WHERE ID = '%d' GROUP BY ID', $ID
  );

  $result = mysql_query($sql);

  $total  = $result ? mysql_fetch_assoc($result)['total'] : 0;

但我不喜欢这个示例代码,因为它使用了mysql_*函数并且 PDO 更好。

于 2013-04-30T02:22:31.073 回答
0

我相信您正在寻找类似的东西:

$total = 0;#initialize
while ($row = mysql_fetch_array($sql)){
      $total += $row['weight'];#adds weight to the total
}
echo $total;
于 2013-04-30T02:21:39.257 回答
0
   $Number_Variable = 0;
  while ($row = mysql_fetch_array($sql)){

  $Number_Variable += $row['weight'];

  }

然后在你完成你的一段时间后:

echo $Number_Variable;
于 2013-04-30T02:21:40.913 回答
0
<?php

  $sum = 0;
  $sql = mysql_query("SELECT weight FROM table WHERE ID = '$ID'");

  while ($row = mysql_fetch_array($sql)){

   $sum = $sum + $row['weight']; 


  }

  echo $sum;


  ?>
于 2013-04-30T02:22:17.343 回答
0
<?php

  $sql = mysql_query("SELECT weight FROM table WHERE ID = '$ID'");

  $total = 0;
  while ($row = mysql_fetch_array($sql)){
    $total = $total + $row['weight'];
  }

    echo $total;

?>
于 2013-04-30T02:22:21.953 回答
0

现在您正在学习开始使用mysqlipdo学习 mysql/php,因为不推荐使用 mysql_* 函数

$mysqli = new mysqli('server', 'database_user', 'database_pass', 'database_name');
if($mysqli->connect_errno) {
    echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$my_query = $mysqli->query("SELECT SUM(weight) as total_weight FROM your_table");
if($my_query->num_rows){
    while($row = $my_query->fetch_assoc()){
       echo 'Total weight is: ' . $row['weight'];
    }
}
于 2013-04-30T02:24:53.113 回答