phparrayssessionsumpersistent-storage

Sum the columnar values accumulated by numerous form submissions


After submitting a form, I receive an indexed array as a SQL-query result and the goal is to sum the column-specific values with previously collected results.

Example:

// 1st query result
$product_amount = [0.36, 0.14, 0.42]

// 2nd query result
$product_amount = [0.28, 0.12, 0.40]

// n-th query result
$product_amount = [0.16, 0.14, 0.42]

// the desired sum
$total = [0.80, 0.40, 1.24]

How to do it?

The code that creates an array:

function doseCount($num){
    return ($num/100) * intval($_POST['portion']); //getting multiplier for productAmount() function
}

function productAmount(){
    global $link; //connection to the MySQL server
    if(isset($_POST['product'])){
        $product_amount_query = 'SELECT va.vitamin_a, va.vitamin_b1, va.vitamin_b2, va.vitamin_b3, va.vitamin_b5, 
                va.vitamin_b6, va.vitamin_bc_b9, va.vitamin_b12, va.vitamin_c, va.vitamin_d, va.vitamin_e, va.biotin, va.vitamin_k, 
                va.flavonoids, va.lipoic_acid FROM products_list p, vitamins_amount va WHERE p.id = va.product_id AND p.name = ?';
            
        $product_amount_stmt = mysqli_prepare($link, $product_amount_query);
        mysqli_stmt_bind_param($product_amount_stmt, "s", $_POST['product']);
        mysqli_stmt_execute($product_amount_stmt);
    
        $result = mysqli_stmt_get_result($product_amount_stmt);

        $product = mysqli_fetch_array($result, MYSQLI_NUM);
    
        return $product_final_result = array_map('doseCount', $product);
        mysqli_stmt_close($product_amount_stmt);
        mysqli_close($link);
   }
}

$product_amount = productAmount();

After submit, the $product_amount array gets new data and this new data must be added to the previously accumulated data.


Solution

  • This problem can be solved with proper use of sessions:

    if (empty($_SESSION['product_amount'])){
        $_SESSION['product_amount'] = $product_amount;
    }else{
        foreach ($_SESSION['product_amount'] as $key => $value) {
            $_SESSION['product_amount'][$key] += $product_amount[$key];
        }
    }
    

    Special thanks to Mawia HL for his help.