Putting values ​​into an array and using array_sum

OK i'm a bit stuck, i know its simple thing missing here so hope fresh eyes help

I have values ​​in a column stored as 2: 7: 99 etc. Each value is split:

Now I can strip out all the values ​​and query another table to get the price that matches that value.

The problem I am having is making the SUM of all price values ​​See code below I think the easiest way is to add all price values ​​to an array and then do array_sum (), but for some reason I just can't get it work

** Please DO NOT SPECIFY SQL Injection .. Its on a LOCAL machine with NO external access and only I 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();
?>

      

Thank you in advance

+3


source to share


3 answers


You're overwriting the final price all the time:

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

      



Replace it like this:

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

      

+2


source


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

with this in your code

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

      



+4


source


The problem with your current approach is that you are overwriting a variable $price

. You need to push a value in an array $price

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

      

+2


source







All Articles