https://kopy.io/6Ud9J https://kopy.io/7tFRb
In first code I have view_cart.php but it doesn't show me the values.
Viewcart.php
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>pret</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION['prodcos'])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION['prodcos'] as $cart_itm)
{
var_dump($cart_itm);
//set variables to use in content below
$titlu = $cart_itm['titlu'];
$cantitate = $cart_itm['cantitate'];
$pret = $cart_itm['pret'];
$id = $cart_itm['id'];
$subtotal = ($pret * $cantitate); //calculate pret x Qty
var_dump($titlu);
var_dump($pret);
var_dump($titlu);
echo '<tr>';
echo '<td><input type="text" size="2" maxlength="2" name="cantitate['.$id.']" value="'.$cantitate.'" /></td>';
echo '<td>'.$titlu.'</td>';
echo '<td>'.$pret.$currency.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$id.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
update_cart.php
<?php
session_start();
include_once("includes/config.php");
//add product to session or create new one
if(isset($_POST['type']) && $_POST['type']=='add' && $_POST['cantitate']>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
$id = $_POST['id'];
$sth = $db->prepare("SELECT titlu, pret FROM produse WHERE id = :id");
$sth->bindParam(':id', $id);
$sth->execute();
// $statement = $db->query('SELECT titlu, pret FROM produse WHERE id="$id"');
while($sth->fetch(PDO::FETCH_ASSOC)){
//fetch product name, pret from db and add to new_product array
$new_product['titlu'] = $titlu;
$new_product['pret'] = $pret;
if(isset($_SESSION['prodcos'])){ //if session var already exist
if(isset($_SESSION['prodcos'][$new_product['id']])) //check item exist in products array
{
unset($_SESSION['prodcos'][$new_product['id']]); //unset old array item
}
}
$_SESSION['prodcos'][$new_product['id']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST['cantitate']) || isset($_POST['remove_code']))
{
//update item quantity in product session
if(isset($_POST['cantitate']) && is_array($_POST['cantitate'])){
foreach($_POST['cantitate'] as $key => $value){
if(is_numeric($value)){
$_SESSION['prodcos'][$key]['cantitate'] = $value;
}
}
}
//remove an item from product session
if(isset($_POST['remove_code']) && is_array($_POST['remove_code'])){
foreach($_POST['remove_code'] as $key){
unset($_SESSION['prodcos'][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST['return_url']))?urldecode($_POST['return_url']):''; //return url
header('Location:'.$return_url);
?>
When I ADD the product, in shopping cart, it doesn't show the details..
Here is my cart code:
function cart() {
$total = 0;
$item_quantity = 0;
$item_name = 0;
$item_number = 1;
$amount = 1;
$quantity = 1;
foreach ($_SESSION as $name => $value) {
if($value > 0 ) {
if(substr($name, 0, 8) == "product_"){
$length = strlen($name - 8);
$id = substr($name, 8 , $length);
$query = query("SELECT * FROM products WHERE product_id = " . escape_string($id)." ");
confirm($query);
$titleArr = array();
while($row = fetch_array($query)) {
$titleArr[$id] = $row['product_title'];
$product_name = implode(",", $titleArr);
$order_product = $product_name . "-". $value;
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$item_number++;
$amount++;
$quantity++;
$id++;
}
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
$_SESSION['item_name'] = $order_product;
}
}
}
}
I searched online for a long time, please advise.
$_SESSION['item_name'] = $order_product;
It gives last value from fetch_array I want all product title on cart page.
Either of these changes should work...
This puts the m all into an array...
$_SESSION['item_name'] = array();
foreach ($_SESSION as $name => $value) {
...
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
array_push($_SESSION['item_name'],$order_product);
...
}
This puts them into a comma separated string...
$_SESSION['item_name'] = '';
foreach ($_SESSION as $name => $value) {
...
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
$_SESSION['item_name'] .= $order_product.', ';
...
}
$_SESSION['item_name'] = rtrim($_SESSION['item_name'],' ');
$_SESSION['item_name'] = rtrim($_SESSION['item_name'],',');
Please make two dimensional Array, if you want to show all product title on cart page.
Replace this
$order_product = $product_name . "-". $value;
with
$order_product[] = $product_name . "-". $value;
Before while loop assign the array:-
$order_product = array();
updated while loop
$total = 0
while($row = fetch_array($query)) {
$titleArr[$id] = $row['product_title'];
$product_name = implode(",", $titleArr);
$order_product = $product_name . "-". $value;
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$item_number++;
$amount++;
$quantity++;
$id++;
$total += $sub;
$_SESSION['item_name'][] = $order_product;
}
$_SESSION['item_total'] = $total;
$_SESSION['item_quantity'] = $item_quantity;
I spent a good 30 minutes looking on this site trying to find an answer to this problem however what ever I seem to try won't fix it.
Right at the end of the php code block. I create a session array called "checkout" where I want to store each of the item's ID inside. This is then passed over to a checkout page where the user will see a summary of what they have ordered/their details.
How ever when I come to the checkout page I can only ever seem to get the last $item_id added to the cart to show up
I think each time the loop runs, the $item_id value is being over written inside the "checkout" array instead of being added onto the end of the array. But I'm just not sure how to fix it.
Any help you can give would be greatly appreciated as I've been sat here for 3 hours now trying to get round this problem.
<?php
$cartOutput ="";
$cartTotal = "0";
$totalVat = "0";
if (!isset($_SESSION["cart_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){
$item_id = $each_item['item_id'];
$sql = mysql_query("SELECT * FROM estock WHERE stockno='$item_id' LIMIT 1");
while ($row = mysql_fetch_array($sql)){
$product_name = $row["description"];
$price = $row["price"];
$details = $row["details"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$totalVat = $cartTotal * 1.175;
//Table
$cartOutput .= '<tr>';
$cartOutput .= '<td> ' . $product_name . '<br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="1" /> </td>';
$cartOutput .= '<td>'.$details.'</td>';
$cartOutput .= '<td>£'.$price.'</td>';
$cartOutput .= '<td>'.$each_item['quantity'].'</td>';
$cartOutput .= '<td>£'.$pricetotal.'</td>';
$cartOutput .= '<td><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></td>';
$cartOutput .= '</tr>';
$_SESSION["checkout"] = array();
$_SESSION["checkout"][] = $item_id;
$i++;
if ($i++ > 3) break;
}
}
?>
Below you can see what I'm doing to retrieve the array on the checkout.php page
I then echo out $cartOutput inside a table.
foreach ($_SESSION["checkout"] as $itemid){
$cartOutput = "";
$item_id = $itemid;
$sql = mysql_query("SELECT * FROM estock WHERE stockno='$item_id' LIMIT 1");
while ($row = mysql_fetch_array($sql)){
$item_id = $row["stockno"];
$product_name = $row["description"];
$price = $row["price"];
$details = $row["details"];
}
$cartOutput .= '<tr>';
$cartOutput .= '<td>'.$item_id.'</td>';
$cartOutput .= '</tr>';
}
?>
The problem is in this line
$_SESSION["checkout"] = array();
Put this line out of the main foreach loop and in the loop add the values in the array. Because each time you are creating new array and thats why you old values are lost.
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']) {
....