I have this code where am able to get data from the database and insert into an array and also be able to insert it back in another table in the same database but what i want is that in the data there is a price and if there is data available either one or two and the price when you sum it together is greater than a specific value then do something
<?php session_start(); require "../db/dbconn.php"; $sql = "SELECT cartPrice FROM cart"; $result = mysqli_query($conn, $sql); $datas = array(); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $datas[] = $row; } } foreach($datas as $data) { $price = $data['cartPrice']; #so how do i do it if $price is greater than maybe 1000 then do this especially when it loops more than one $stmt = $conn->prepare("INSERT INTO order (price) VALUES (?)"); $stmt->bind_param("s", $price); $stmt->execute(); }
Does anybody know how i can do this and if you don’t understand i can still explain to you
Advertisement
Answer
What I understood from your question is that you want to calculate the sum of prices in the $datas array and apply some condition on that sum of prices. Well, you can simply just create a variable and keep adding $price in it. Then at the end of loop, apply your condition.
$totalPrice = 0; foreach($datas as $data) { $price = $data['cartPrice']; $totalPrice = $totalPrice + $price $stmt = $conn->prepare("INSERT INTO order (price) VALUES (?)"); $stmt->bind_param("s", $price); $stmt->execute(); } if($totalPrice > 1000) { # DO SOMETHING }