duanbi9202 2018-07-16 03:45
浏览 55
已采纳

在PHP中为每个添加总和

$connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");

foreach($a as $b){ 
    foreach($b as $c){
        $query5 = "SELECT P_price tbl_products WHERE PID='".$c['PID']."' ";
        $get_price = mysqli_query($connect, $query5);
        $get_price1 = mysqli_fetch_assoc($get_price); 
        $price = ($get_price1['P_price'])+ $price + 0; // This does not add
    }
}

$price does not add only takes the last value of the data inside the loop.

How can I add them?

I also used:

$price = ($get_price1['P_price'])+0;
$new_price += $price;

Still failed.
Thank You!

  • 写回答

2条回答 默认 最新

  • doushang8512 2018-07-16 04:14
    关注

    initialise $price before looping through the array.

    $connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");
    
    $price = 0;
    foreach($b as $c)
    {
      $query5 = "select P_price from tbl_products where PID='".$c['PID']."' ";
      $get_price = mysqli_query($connect, $query5);
      $get_price1 = mysqli_fetch_assoc($get_price); 
      $price = ($get_price1['P_price'])+$price;
      // other way (highly recommended)
      $price += ($get_price1['P_price']);
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部