I've coded out my cart page and it seems that it is not showing anything. Previously on my product page, I have a form action that will lead me to cart.php upon clicking add to cart. I am not sure what went wrong here.
<?php
session_start();
//script error reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to the MySQL database
include "storescripts/connect.php";
?>
<?php
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// if the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// run if the cart is empty or not set
$_SESSION["cart_array"] = array(1 => array("item_id" => $pid, "quantity" => 1));
} else {
// run if the cart has at least one item in it
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $pid) {
//that item is in cart already so let's adjust its quantity using array_slice()
array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} //close if condition
}//close while loop
}//close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
}
}
?>
<?php
// SECTION 2(if user chooses to empty their shopping cart)
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
unset($_SESSION["cart_array"]);
}
?>
<?php
// SECTION 3 (render the cart for the user to view)
$cartOutput = "";
if (!isset($_SESSION["crt_array"]) || count($_SESSION["cart_array"]) < 1) {
$cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
$item_id = $each_item["item_id"];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
while ($row = mysql_fetch_array($sql)) {
$product_name = $row["product_name"];
$price = $row["price"];
}
$cartOutput .= "<h2>Cart Item $i</h2>";
//while(list($key, $value) = each($each_item))
// $cartOutput .= "$key: $value<br/>";
$cartOutput .= "Item ID:" . $each_item['item_id'] . "<br/>";
$cartOutput .= "Item Quantity:" . $each_item['quantity'] . "<br/>";
$cartOutput .= "Item Name:" . $product_name . "<br/>";
$cartOutput .= "Item Price: $" . $price . "<br/>";
}
}
?>
You have a minor error there. Spelling mistake my dear. It happens. Human error always happens(: And its at session cart array(:
Related
I am making a shopping cart system, and my session is being displayed with a foreach() function. Inside this function, i have a variable called $item_price. I would like all the $item_price's to be added up so that I end up with the grand total.
How could this be done? I have no clue to how this problem should be solved :/
This is my foreach() code:
foreach($session_cart as $cart_items) {
$fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'");
while($shop_items = mysql_fetch_array($fetch_info)) {
$item_id = $shop_items['item_id'];
$item_name = $shop_items['item_name'];
$item_quantity = count(array_keys($session_quantity, $item_id));
$item_price = $shop_items['item_price'] * $item_quantity; }
$cartOutput .= '<h2>'.$item_name.'</h2>';
$cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>';
$cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>';
$cartOutput .= '<a> ID: '.$item_id.'</a><br><br>';
}
Use updated code:
$total = 0;
foreach($session_cart as $cart_items) {
$fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'");
// while($shop_items = mysql_fetch_array($fetch_info)) { //<- No need of loop here as only one will be returned everytime
$shop_items = mysql_fetch_assoc($fetch_info); //<- use this instead
$item_id = $shop_items['item_id'];
$item_name = $shop_items['item_name'];
$item_quantity = count(array_keys($session_quantity, $item_id));
$item_price = $shop_items['item_price'] * $item_quantity;
//} //<- Closing while loop removed
$cartOutput .= '<h2>'.$item_name.'</h2>';
$cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>';
$cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>';
$cartOutput .= '<a> ID: '.$item_id.'</a><br><br>';
$total+=$item_price; //<- Sums up for grand total
}
echo $total; //<- shows grand total
$total = 0;
foreach($array as $row)
{
$total += $row['item_price'];
//the rest of your code in foreach
}
echo $total;
I was doing the shopping cart tutorial, following http://www.youtube.com/watch?v=WXqbQy9fOp8.
I followed the code closely, but couldn't get the same outcome.
my item id and quantity suppose to be shown when I click add to cart, however, only my quantity shown. Can someone tell me what's is wrong with my code?
Thanks
here is my coding..
<?php
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["supermarketcart"] = array(1 => array("id" => $pid, "quantity" => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["supermarketcart"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "id" && $value == $pid) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["supermarketcart"], $i-1, 1, array(array("id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["supermarketcart"], array("id" => $pid, "quantity" => 1));
}
}
header("location: cart.php");
exit();
}
?>
<?php
//if user choose to empty cart
if(isset($_GET['cmd']) && $_GET['cmd'] == "emptycart")
{
unset($_SESSION["supermarketcart"]);
}
?>
<?php
//render the cart for user to view
$cartOutput = "";
if(!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1 ){
$cartOutput = "<h2 align = 'center'> Your shopping cart is empty</h2>";
}
else
{
$i = 0;
foreach ($_SESSION["supermarketcart"] as $each_item)
{
$i++;
$cartOutput = "<h2>Cart Item $i</h2>";
while(list($key,$value) = each($each_item))
{
$cartOutput ="$key:$value</br>";
}
}
}
?>
You need to append cartOutput in loop. you have re assigned cartOutput in each time.
try like this:
$cartOutput = "";
if(!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1 ){
$cartOutput .= "<h2 align = 'center'> Your shopping cart is empty</h2>";
}
else
{
$i = 0;
foreach ($_SESSION["supermarketcart"] as $each_item)
{
$i++;
$cartOutput .= "<h2>Cart Item $i</h2>";
while(list($key,$value) = each($each_item))
{
$cartOutput .="$key:$value</br>";
}
}
}
$cartOutput = "<h2>Cart Item $i</h2>";
$cartOutput = "$key:$value</br>"
Problem is in these lines. You are rewriting the cartOutput variable at every step of the loop (thus clearing the 'id').
You should append the data instead:
$cartOutput .= "<h2>Cart Item $i</h2>";
$cartOutput .= "$key:$value"
I was doing a shopping cart tutorial,
I met with one error stating that my item_id is not defined
for $cartOutput .= "Item ID: " . $each_item['item_id']."<br>";
However,
I have defined the item_id.
here is my code.
Can someone tell me what's wrong?
<?php
//script error reporting
error_reporting(E_ALL);
ini_set('display_errors','1');
?>
<?php
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["supermarketcart"][] = array(1 => array("item_id" => $pid, "quantity" => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["supermarketcart"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $pid) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["supermarketcart"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["supermarketcart"], array("item_id" => $pid, "quantity" => 1));
}
}
header("location: cart.php");
exit();
}
?>
<?php
//if user choose to empty cart
if(isset($_GET['cmd']) && $_GET['cmd'] == "emptycart")
{
unset($_SESSION["supermarketcart"]);
}
?>
<?php
//render the cart for user to view
$cartOutput = "";
if(!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1 ){
$cartOutput .= "<h2 align = 'center'> Your shopping cart is empty</h2>";
}
else
{
$i = 0;
foreach ($_SESSION["supermarketcart"] as $each_item)
{
$i++;
$item_id = $each_item['item_id'];
$sql = mysql_query("SELECT * FROM supermarket WHERE id = '$item_id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
$product_des = $row_supermarketDetails['description'];
$price = $row_supermarketDetails['price'];
}
$cartOutput .= "<h2>Cart Item $i</h2>";
$cartOutput .= "Item ID: " . $each_item['item_id']."<br>";
$cartOutput .= "Item Quatity: " . $each_item['quantity']."<br>";
$cartOutput .= "Item Name: " . $product_des."<br>";
$cartOutput .= "Item Price: " . $price."<br>";
}
}
?>
Your array structure is complicated, and you have a multidimensional array like sp
array (
array (
"item_id" => $ pid, "quantity" => 1
)
)
So you need adjust your code
if (!isset($_SESSION["supermarketcart"]) || count($_SESSION["supermarketcart"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["supermarketcart"][] = array(1 => array("item_id" => $pid, "quantity" => 1));
}
add [] to your $_SESSION["supermarketcart"] statement like you see above
I'm just learning how to use this StackOverflow, so please bear with me. If you need anything further I can provide it. I can click the checkmark on your answer if you can help me.
My code is working, but there is a small glitch. Currently, I have $i=0 and my code deletes the $i from the form. The problem is that with, for example, when $i=2 is deleted, $i=3 becomes $i=2, and I can no longer delete that item from my cart, because it is now the same $i that was deleted.
Here is my code:
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
header("location: cart.php");
} else {
unset($_SESSION["cart_array"]["$key_to_remove"]);
//sort($_SESSION["cart_array"]);
}
}
And here is my output loop:
$cartoutput = "";
$cartTotal="";
$totalwithtaxdisplay = 0;
$servicechargedisplay =0;
$grandtotaldisplay = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<div align='center'><font style='font-weight: bold; font-size: 20pt;'>Your order is currently empty.</font></div>";
}else{
$i=0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$item_id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
//echo mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
//item id is $each_item['item_id']; being pulled in from form on other page PID.
$id = $row['id'];
$product_name = $row["name"];
$price = $row["price"];
$description = $row['description'];
}
$tax = .065;
$service = .18;
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$totalwithtax = round($cartTotal + ($cartTotal * $tax), 2); //Order Items + Tax
$totalwithtaxdisplay = number_format($totalwithtax, 2, '.', ''); //displays the decimals correctly
$servicecharge = round($totalwithtax * $service, 2); //service charge
$servicechargedisplay = number_format($servicecharge, 2, '.', ''); //displays the decimals correctly
$grandtotal = round($totalwithtax + ($totalwithtax * $service), 2); //service charge
$grandtotaldisplay = number_format($grandtotal, 2, '.', ''); //displays the decimals correctly
$cartoutput .= " <tr><td width='20%'> Order Item $i </td>
<td width='40%'> " . $product_name . "</td>
<td width='20%'> $" . $price . ".00</td>";
$cartoutput .=" <td width='20%'><form action='cart.php' method='post'>
<input name='deleteBtn" . $item_id . "'type='submit' value='Remove This Item' />
<input name='index_to_remove' type='hidden' value='" . $i . "' />
</form></td></tr>";
$i++;
}
}
I echo out the $cartouput at a later time. You can see in the code above the second $cartouput is the form i'm using. It hold the value $i, but when that value is deleted, it doesn't let me delete the item that has updated into the new $i.
Instead of setting index_to_remove to $i, you should set it to $item_id and in your session variable. That way, you no longer need $i.
Also, this line leaves you with an SQL injection vulnerability: $item_id = $each_item['item_id'];. You should, at minimum, escape it using mysqli_real_escape_string().
My problem is I am having a cart_array which store the product added into my cart. when I press submit and process through the first block of php, if there's sufficient data, it should go to the unset($_SESSION['cart_array']); part and destroy the cart_array, however, it does not do so, the item added still show up in my cart.php. I tried session_destroy also no luck. Thing to note is that it does echo out $success which means the code should pass through that part but why it didn't unset my cart_array?
<?php
if ($_POST['cartOutput']) {
$customer_name = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_name']);
$tel_num = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['tel_num']);
$customer_address = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_address']);
$customer_messages = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_messages']);
$error_status = false;
if (empty($customer_name)){
$error_customer_name ='<h4>Please Fill Your Name</h4>';
$error_status = true;
}
if (empty($tel_num)){
$error_tel_num='<h4>Please Fill Your Contact Number</h4>';
$error_status = true;
}
if (empty($customer_address)){
$error_customer_address='<h4>Please Fill Your Address</h4>';
$error_status = true;
}
if(!$error_status) {
include "storescripts/connect_to_mysqli.php";
$sql= 'INSERT INTO orders (customer_name,tel_num,customer_address,product_name, price, quantity, date_added,customer_messages) VALUES(?,?,?,?,?,?,NOW(),?)';
$stmt = $myConnection->prepare($sql);
$countArray = count($_POST["item_name"]);
for ($i = 0; $i < $countArray; $i++) {
$stmt->bind_param('sssssss', $customer_name,$tel_num,$customer_address, $_POST['item_name'][$i], $_POST['amount'][$i], $_POST['quantity'][$i],$customer_messages);
$stmt->execute();
}
;
$to_address="someone#gmail.com";
$subject="Online Store Order Submission";
$cartTotal=$_POST['cartTotal'];
$message="Input from online order form.\n\n";
$message .="Name: ".$customer_name."\n";
$message .="Tel: ".$tel_num."\n";
$message .="Address: ".$customer_address."\n";
$message .="Messages: ".$customer_messages."\n";
$message .="Total:".$cartTotal."\n";
mail($to_address, $subject, $message);
$success= 'ORDER SUMITTED SUCCESSFULLY! Thank you and WELCOME to shop again!';
unset($_SESSION["cart_array"]);
}
}
?>
another thing to note is when I make the form action posted to another file let's say order.php and put the above code in it, it UNSET the session, of cause i change the POST to ISSET and put exit() after the unset thou, when i try to put exit() in my cart.php it just go blank if it submitted succesffully.
any help would be appreciated
The below are all the PHP BLOCK above HTML tag for the reference.
<?php
if ($_POST['cartOutput']) {
$customer_name = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_name']);
$tel_num = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['tel_num']);
$customer_address = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_address']);
$customer_messages = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_messages']);
$error_status = false;
if (empty($customer_name)){
$error_customer_name ='<h4>Please Fill Your Name</h4>';
$error_status = true;
}
if (empty($tel_num)){
$error_tel_num='<h4>Please Fill Your Contact Number</h4>';
$error_status = true;
}
if (empty($customer_address)){
$error_customer_address='<h4>Please Fill Your Address</h4>';
$error_status = true;
}
if(!$error_status) {
include "storescripts/connect_to_mysqli.php";
$sql= 'INSERT INTO orders (customer_name,tel_num,customer_address,product_name, price, quantity, date_added,customer_messages) VALUES(?,?,?,?,?,?,NOW(),?)';
$stmt = $myConnection->prepare($sql);
$countArray = count($_POST["item_name"]);
for ($i = 0; $i < $countArray; $i++) {
$stmt->bind_param('sssssss', $customer_name,$tel_num,$customer_address, $_POST['item_name'][$i], $_POST['amount'][$i], $_POST['quantity'][$i],$customer_messages);
$stmt->execute();
}
;
$to_address="someone#gmail.com";
$subject="Online Store Order Submission";
$cartTotal=$_POST['cartTotal'];
$message="Input from online order form.\n\n";
$message .="Name: ".$customer_name."\n";
$message .="Tel: ".$tel_num."\n";
$message .="Address: ".$customer_address."\n";
$message .="Messages: ".$customer_messages."\n";
$message .="Total:".$cartTotal."\n";
mail($to_address, $subject, $message);
$success= 'ORDER SUMITTED SUCCESSFULLY! Thank you and WELCOME to shop again!';
unset($_SESSION["cart_array"]);
}
}
?>
<?php
session_start();
/* Created by Adam Khoury # www.developphp.com */
// Connect to the MySQL database
include "storescripts/connect_to_mysqli.php";
// Query the module data for display ---------------------------------------------------------------------------------------------------------------
$sqlCommand = "SELECT modulebody FROM modules WHERE showing='1' AND name='footer' LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$footer = $row["modulebody"];
}
mysqli_free_result($query);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
// Query the module data for display ---------------------------------------------------------------------------------------------------------------
$sqlCommand = "SELECT modulebody FROM modules WHERE showing='1' AND name='custom1' LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$custom1 = $row["modulebody"];
}
mysqli_free_result($query);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
// Build Main Navigation menu and gather page data here -----------------------------------------------------------------------------
$sqlCommand = "SELECT id, linklabel FROM pages WHERE showing='1' ORDER BY id DESC";
$query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
$menuDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$linklabel = $row["linklabel"];
$menuDisplay .= '<a href="index.php?pid=' . $pid . '">' .
$linklabel . '</a><br />';
}
mysqli_free_result($query);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
//mysqli_close($myConnection);
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
// Script Error Reporting
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 1 (if user attempts to add something to the cart from the product page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $pid) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
}
header("location: cart.php");
exit();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 2 (if user chooses to empty their shopping cart)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_GET['cmd']) && $_GET['cmd'] === 'emptycart') {
unset($_SESSION["cart_array"]);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 3 (if user chooses to adjust item quantity)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
// execute some code
$item_to_adjust = $_POST['item_to_adjust'];
$quantity = $_POST['quantity'];
$quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
if ($quantity >= 100) {
$quantity = 99;
}
if ($quantity < 1) {
$quantity = 1;
}
if (empty($quantity)) {
$quantity = 1;
}
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $item_to_adjust) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
} // close if condition
} // close while loop
} // close foreach loop
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 4 (if user wants to remove an item from cart)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] !== '') {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
} else {
unset($_SESSION["cart_array"][$key_to_remove]);
sort($_SESSION["cart_array"]);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 5 (render the cart for the user to view on the page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$cartOutput = "";
$cartTotal = "";
$pp_checkout_btn = '';
$product_id_array = '';
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
$cartOutput = "<h3 align='center'>Your shopping cart is empty</h3>";
} else {
// Start PayPal Checkout Button
$pp_checkout_btn .= '<form action=" " method="post">
<input type="hidden" name="cartOutput" value = "$cartOutput">';
// Start the For Each loop
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$sqlCommand = "SELECT * FROM products WHERE id='$item_id' LIMIT 1";
$sql = mysqli_query($myConnection, $sqlCommand);
while ($row = mysqli_fetch_array($sql)) {
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
setlocale(LC_MONETARY, "ms_MY");
$pricetotal = money_format("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$pp_checkout_btn .= '<input type="hidden" name="item_name[]" value="' . $product_name . '">
<input type="hidden" name="amount[]" value="' . $price . '">
<input type="hidden" name="quantity[]" value="' . $each_item['quantity'] . '"> ';
// Create the product array variable
$product_id_array .= "$item_id-" . $each_item['quantity'] . ",";
// Dynamic table row assembly
$cartOutput .= "<tr>";
$cartOutput .= '<td><center>' . $product_name . '<br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="0" /></center></td>';
$cartOutput .= '<td>' . $details . '</td>';
$cartOutput .= '<td><center>RM' . $price . '</center></td>';
$cartOutput .= '<td><center><form action="cart.php" method="post">
<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
<input name="adjustBtn' . $item_id . '" type="submit" value="change" />
<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
</form></center></td>';
//$cartOutput .= '<td><center>' . $each_item['quantity'] . '</center></td>';
$cartOutput .= '<td><center>' . $pricetotal . '</center></td>';
$cartOutput .= '<td><center><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></center></td>';
$cartOutput .= '</tr>';
$i++;
}
setlocale(LC_MONETARY, "ms_MY");
$cartTotal = money_format("%10.2n", $cartTotal);
$cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : " . $cartTotal . " MYR</div>";
// Finish the Paypal Checkout Btn
$pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
<div id="table">
Name: <input type="text" name="customer_name">
<br/>
Tel: <input type="text" name="tel_num">
<br/>
Address: <input type="text" name="customer_address">
<br/>
Messages: <textarea name="customer_messages">
</textarea>
<input type="hidden" name="cartTotal" value="' . $cartTotal . '">
<input type="submit" value="Submit">
</div>
</form>';
}
?>
If you want to manipulate the session as in unset($_SESSION["cart_array"]); you have to have a session to manipulate.
So if you add a session_start(); at the top of the first piece of code, it will probably unset correctly
As in :-
<?php
session_start();
if ($_POST['cartOutput']) {
....