Putting values into an array and using array_sum

324 Views Asked by At

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

3

There are 3 best solutions below

3
On BEST ANSWER

You are all the time overwriting you final price:

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

Replace that with:

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

The issue with your current approach is you are overwriting the $price variable. You need to push the value in the $price array like $price[] = $pricer['incvat']. You need to do 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[] = $pricer['incvat'];

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

        }

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

    $total = array_sum($price);
    echo $total;
}
basicTotal();
?>
0
On
just replace  $price = $pricer['incvat']; 

with this in your code

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