How to unset / destroy session that retrieves data from mysql - php
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']) {
....
Related
Shopping Cart no values
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..
Insert array values into mysql database
The variables are being posted from a previous page through array values. when I print_r($values) I get the whole value on this array including the numerical values of the array ex: array[0], array[1] ..etc. Please can some tell me what I am doing wrong. the implode function was not used because the values are passed from a cart page though session variables. First part of code below: <?php $current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); if(isset($_SESSION["products"])) { $total = 0; echo '<form method="post" action="process.php">'; echo '<ul>'; $cart_items = 0; foreach ($_SESSION["products"] as $cart_itm) { $product_code = $cart_itm["code"]; $results = $mysqli->query("SELECT Title,Description,Price FROM main_menu WHERE MenuID='$product_code' LIMIT 1"); $obj = $results->fetch_object(); echo '<li class="cart-itm">'; echo '<span class="remove-itm">×</span>'; echo '<div class="p-price">'.$currency.$obj->Price.'</div>'; echo '<div class="product-info">'; echo '<h3>'.$obj->Title.' (Code :'.$product_code.')</h3> '; echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>'; echo '<div>'.$obj->Description.'</div>'; echo '</div>'; echo '</li>'; $subtotal = ($cart_itm["price"]*$cart_itm["qty"]); $total = ($total + $subtotal); echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />'; echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />'; echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->Description.'" />'; echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />'; $cart_items ++; } echo '</ul>'; echo '<span class="check-out-txt">'; echo '<strong>Total : '.$currency.$total.'</strong> '; echo '<input name=\'submit\' type="submit" value="Complete Order" style=\"width:150px;background:#333;color:#ffcc33;height:30px;\" />'; echo '</span>'; echo '</form>'; }else{ echo 'No items added'; } ?> Second part:
Try $post and the table name in the given function and use mysql_real_escape_string() to avoid any possibility of the SQL Injection form.php <?php include ('func_curd.php') ; if($_POST['hiddenfieldinfo']=='ok') { $r=insert_your_table_name($_POST); if($r==true) { header('Location:'.get_full_url()); /* to redirect the form to the same page after successful submission*/ } } ?> func_curd.php <?php function insert_your_table_name($post) { unset($post['hiddenfieldinfo']); /* Here I am unsetting this value as it is hidden field in the form , which I am using as form submission check and is not in database column, apart form auto-increment in database that is id, you have to maek sure all the post value and column name matches with case-sensitivities */ $u = insert('your_table_name', $post); $r=is_numeric($u)? true : false ; return $r; } function insert($table, $values){ $query="INSERT INTO `$table` "; $column='('; $val=' ('; $count=count($values); $mk=1; foreach ($values as $key=>$value) { $value=mysql_real_escape_string($value); if ($mk==$count) { $column .= '`'.$key.'`'; $val .= "'".$value."'"; } else { $column .= '`'.$key.'`, '; $val .= "'".$value."', "; } $mk++; } $column .=') '; $val .=')'; $query=$query.$column.'VALUES'.$val; $Q=mysql_query($query); if(mysql_error()) { return print(mysql_error()); } else { $insert_id=mysql_insert_id(); return $insert_id; } } ?>
try this one: <?php require_once('config/connect.php'); $item_name = strip_tags($_POST['item_name']); $item_code = strip_tags($_POST['item_code']); $item_desc = strip_tags($_POST['item_desc']); $item_qty = strip_tags($_POST['qty']); $price = strip_tags($_POST['price']); $fields = "item_name, item_code, item_desc, price,qty"; $query = "INSERT INTO `x` SET "; $i = 0; foreach( $fields as $fieldname ) { if ( $i > 0 ) $query .= ", "; $val = strip_tags($_POST[$fieldname]); $query .= "`" . $fieldname . "` = '" . $val . "'" $i++ } $query_result = mysql_query($query); echo" Record saved"; print_r ( $query ); ?> There are certain syntax errors in your code like not closed foreach etc. whihc I did skip. As a recommendation: code like this is disclosing the database structure to everyone on the internet - form field names = database col names. This is generally a bad idea. Better is a kind of mapping table: $fields = array ( 'myFormName' => 'mySqlName', .... foreach( $fields as $fieldname => $sqlame) { if ( $i > 0 ) $query .= ", "; $val = strip_tags($_POST[$fieldname]); $query .= "`" . $sqlname. "` = '" . $val . "'" .... which also will make the form more independent from the underlying data structures.
Array value being over written by newest value inside loop
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.
Deleting an item from my shopping cart using PHP and MySQL
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().
cart page is not showing anything
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(: