如何在 php 中的 while 循环结果中添加值

How to add values to in the result of while loop in php

如何添加存储在变量$profit 中的while 循环结果?结果是 5 和 70

代码

  <?php
        $sql2 = "SELECT * from `products`";
        $result2 = $link->query($sql2);

        while($row2 = $result2->fetch_assoc())
      {

      $sql3 = "SELECT * from `orders` where product_id = '".$row2['prod_id']."'";
      $result3 = $link->query($sql3);
      $row3 = $result3->fetch_assoc();
      
      $sql = "SELECT  SUM(product_qty) from orders where product_id = '".$row2['prod_id']."'";
      $result = $link->query($sql);
      $row = mysqli_fetch_array($result);

      $res = bcmul($row2['prod_price'], $row[0]);
      $profit = $res - $row2['prod_cost'];

      if($row[0] == null){
          $row[0] = 0;
      }
    }?>

试试这个代码

  <?php
        $sql2 = "SELECT * from `products`";
        $result2 = $link->query($sql2);
        $totalProfit = 0;
        while($row2 = $result2->fetch_assoc())
      {

      $sql3 = "SELECT * from `orders` where product_id = '".$row2['prod_id']."'";
      $result3 = $link->query($sql3);
      $row3 = $result3->fetch_assoc();
      
      $sql = "SELECT  SUM(product_qty) from orders where product_id = '".$row2['prod_id']."'";
      $result = $link->query($sql);
      $row = mysqli_fetch_array($result);

      $res = bcmul($row2['prod_price'], $row[0]);
      $profit = $res - $row2['prod_cost'];
      $totalProfit = $totalProfit + $profit
      if($row[0] == null){
          $row[0] = 0;
      }
    }?>

现在您可以使用 $totalProfit 变量值作为总数。