Php 查找数组中的值之和

Php 查找数组中的值之和,php,mysql,Php,Mysql,我试图从购物车表中选择小计并求和,但无法求和 <?php // This will get all related products mysqli_select_db($conn, $dbname); $query_gettotal = "SELECT subtotal FROM cart WHERE scode ='$gu'"; $gettotal = $conn->query($query_gettotal); $row

我试图从购物车表中选择小计并求和,但无法求和

<?php
    // This will get all related products
    mysqli_select_db($conn, $dbname);
    $query_gettotal = "SELECT subtotal FROM cart WHERE scode ='$gu'";
    $gettotal = $conn->query($query_gettotal);
    $row_gettotal = mysqli_fetch_assoc($gettotal);
    do{ 
    $a = array($row_gettotal['subtotal']); 
    foreach ($a as $value) {
    //print $value;
    //print_r($a);
    //getting value 190047509503800
    // how to add 1900 4750 950 3800
    
    }
    } while ($row_gettotal = mysqli_fetch_assoc($gettotal));

您应该使用准备好的语句来避免SQL注入的任何风险。您还可以直接将查询中的值相加:

$query\u gettotal=“从购物车中选择SUM(小计)作为总计,其中scode=?”;
$stmt=$conn->prepare($query\u gettotal);
$stmt->bind_参数('s',$gu);
$stmt->execute();
$result=$stmt->get_result();
$row_gettotal=$result->fetch_assoc();
$total=$row_gettotal['total'];

您可以使用本机sql获取字段的总和,如:
“从购物车中选择总和(小计),其中scode='$gu'”
,之后您不需要使用循环方法。@DereckSmithElijah无需担心-我很高兴能帮上忙。