Stan Howe Stan Howe - 3 years ago 147
PHP Question

PHP: How to store cart data (foreach loop) into different variables to store in MySQL

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:


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...";


This produces all of the data i need:

Product Details Acquired:

Product Details Acquired:
Double Bed

User details acquired

Would appreciate any help :)

Answer Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download