Good afternoon,
I have searched for an answer to this query and the closest I could find was this: Storing elements in an array at each iteration of a foreach on PHP
I am building my own eCommerce platform using PHP and I have gotten to the point now where I can add items to my cart.
I am currently building the checkout page but I dont know how to store each product ordered into different variables so that I can store them into MySQL.
The following code allows me to populate the relevant data I just dont know how to store this data into the variables:
<?php
session_start();
include '../connection.php';
$cartProducts = array();
foreach ($_SESSION["cart_item"] as $item){
echo "Product Details Acquired:" . "<br>";
echo $item["product_name"] . "<br>";
echo $item["quantity"] . "<br>";
echo "£".$item["product_price"] . "<br> <br>";
}
//setting username variable
$myusername = $_SESSION['login_user'];
// getting client info
include '../connection.php';
$sql="SELECT id, username, phone, email from clients WHERE username='$myusername'";
if ($result = mysqli_query($connection, $sql)){
//Presenting data from array
while ($row = mysqli_fetch_array($result)) {
$client_id= $row['id'];
$client_phone= $row['phone'];
$client_user= $row['username'];
$client_email= $row['email'];
echo "User details acquired" ."<br>";
echo $client_id ."<br>";
echo $client_phone ."<br>";
echo $client_user ."<br>";
echo $client_email ."<br>";
}
}
else {
echo "No client data found...";
}
?>
Why don't you use INSERT
query in your foreach
loop like this:
foreach ($_SESSION["cart_item"] as $item){
// use your product attributes like this.
$product_name = $item["product_name"];
$quantity = $item["quantity"];
// then use insert query like this
$insert = "INSERT INTO products (`product_name`, .. other columns ..) VALUES ('$product_name', .. other column values ..)";
mysqli_query($connection, $insert);
}