Search code examples
phparraysmysqliarray-sum

Putting values into an array and using array_sum


ok im a little stuck, i know its a simple thing im missing here so hoping fresh eyes will help

I have values in a column stored as 2:7:99 etc each value is seperated by :

Now I can seperate all the values out and query another table to get the price which corresponds to that value.

The issue i'm having is doing a SUM of all the price values See code below I think the easiest way would be to add all the price values into an array and then do array_sum() but for some reason i just cant get it working

** Please DO NOT Mention SQL Injection .. Its on a LOCAL machine with NO outside access and only myself will be using this

    <?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();
?>

Thanks in advance


Solution

  • You are all the time overwriting you final price:

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

    Replace that with:

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