将值放入数组并使用 array_sum

Putting values into an array and using array_sum

好吧,我有点卡住了,我知道我在这里遗漏了一件简单的事情,所以希望新鲜的眼睛能有所帮助

我在存储为 2:7:99 的列中有值,每个值由以下分隔:

现在我可以将所有值分开并查询另一个 table 以获得对应于该值的价格。

我遇到的问题是对所有价格值求和 见下面的代码 我认为最简单的方法是将所有价格值添加到一个数组中,然后执行 array_sum() 但由于某种原因我无法让它工作

** 请不要提及 SQL 注入 .. 它在没有外部访问权限的本地机器上,只有我自己会使用这个

    <?php
include('config.php');
// Function for calculation Rough Invoice Total
function basicTotal() {
    $con = mysqli_connect("localhost","USER","PASS","TABLE");
    $wtbdq = mysqli_query($con,"SELECT * FROM `jobs` WHERE wsjid = '18'");
    $wtbdr = mysqli_fetch_assoc($wtbdq);
    do {
    $wtbd = explode(":",$wtbdr['worktobedone']);
    foreach($wtbd as $item) 
        {
            $priceq = mysqli_query($con,"SELECT * FROM `workshop-items` WHERE wsiid = '$item'");
            $pricer = mysqli_fetch_assoc($priceq);

            $price = array($pricer['incvat']);

            echo $item.' - '. $pricer['incvat'].'<br>';

        }

    } while($wtbdr = mysqli_fetch_assoc($wtbdq));

    $total = array_sum($price);
    echo $total;
}
basicTotal();
?>

提前致谢

您当前方法的问题是您正在覆盖 $price 变量。您需要像 $price[] = $pricer['incvat'] 一样将 $price 数组中的值压入。你需要这样做

    <?php
include('config.php');
// Function for calculation Rough Invoice Total
function basicTotal() {
    $con = mysqli_connect("localhost","USER","PASS","TABLE");
    $wtbdq = mysqli_query($con,"SELECT * FROM `jobs` WHERE wsjid = '18'");
    $wtbdr = mysqli_fetch_assoc($wtbdq);
    do {
    $wtbd = explode(":",$wtbdr['worktobedone']);
    foreach($wtbd as $item) 
        {
            $priceq = mysqli_query($con,"SELECT * FROM `workshop-items` WHERE wsiid = '$item'");
            $pricer = mysqli_fetch_assoc($priceq);

            $price[] = $pricer['incvat'];

            echo $item.' - '. $pricer['incvat'].'<br>';

        }

    } while($wtbdr = mysqli_fetch_assoc($wtbdq));

    $total = array_sum($price);
    echo $total;
}
basicTotal();
?>

您一直在改写您的最终价格:

$price = array($pricer['incvat']);

将其替换为:

$price[] = $pricer['incvat'];
just replace  $price = $pricer['incvat']; 

with this in your code

$price[] = $pricer['incvat'];