PHP - 从while循环获取值

时间:2013-04-30 02:18:55

标签: php arrays foreach

很抱歉提出一个简单的问题。

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

例如,使用while($row = mysql_fetch_assoc($sql)),我查询并回显了一个列名称“weight”,在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

我想要执行ADDITION。

30 + 15 + 20 + 35 = 100

7 个答案:

答案 0 :(得分: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要好得多。

答案 1 :(得分:3)

在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'];

另请注意,从PHP 5.5开始,mysql函数已被弃用,将来会被删除,您需要查看mysqli_queryPDO::query

答案 2 :(得分:0)

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

$total = 0;#initialize
while ($row = mysql_fetch_array($sql)){
      $total += $row['weight'];#adds weight to the total
}
echo $total;

答案 3 :(得分:0)

   $Number_Variable = 0;
  while ($row = mysql_fetch_array($sql)){

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

  }

然后在你完成了一段时间之后:

echo $Number_Variable;

答案 4 :(得分: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;


  ?>

答案 5 :(得分: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;

?>

答案 6 :(得分:0)

现在您正在学习使用mysqlipdo开始学习mysql / php mysql_* functions are deprecated

$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'];
    }
}