PHP SQL继续使用之前的内部循环添加row ['value']

时间:2017-11-08 14:58:55

标签: php sql

这是我的代码 -

$sql="SELECT * FROM payment WHERE customerid='$id'";
if ($result=mysqli_query($con,$sql))
  {
  while ($row=mysqli_fetch_assoc($result);
    {
    echo $row['fraction_payment'];
    }    
}

我想尝试做什么:不断添加$row['fraction_payment']与之前的值。

如果数据库值为

fraction_payment 1 = 100 
fraction_payment 2 = 200 
fraction_payment 3 = 300

预期结果将是:

$row['fraction_payment'][1] = 100
$row['fraction_payment'][2] = 300
$row['fraction_payment'][3] = 600

我应该如何在PHP中继续这样做?

2 个答案:

答案 0 :(得分:1)

这应该是诀窍,非常自我解释:

$total = 0;
$sql="SELECT * FROM payment WHERE customerid='$id'";
if ($result=mysqli_query($con,$sql))
{
  while ($row=mysqli_fetch_assoc($result);
  {
    $total += $row['fraction_payment'];
    echo $total;
  }    
}

答案 1 :(得分:1)

$sql="SELECT * FROM payment WHERE customerid='$id'";
if ($result = mysqli_query($con,$sql))
{
  $sum = 0;
  $result = [];
  while ($row = mysqli_fetch_assoc($result);
  {
    $sum += $row['fraction_payment'];
    $result[] = $sum;
  }
  var_dump($result);
}

并且不要忘记SQL注入:How can I prevent SQL injection in PHP?