Why doesn't my id shown in the page - php

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"

Related

PHP add up all values from foreach()

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;

Products not being added to cart

Am having issues with my cart script, i've managed to get it to work by adding an item to the cart, but its not allowing any more items to be added but rather it allows the quantity to be added even when i add another item, its the quantity of the first item that will be increased, here is my code snippet
This my function script that wrietes and generates the cart
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have '.count($items).' item'.$s.' in your shopping cart</p>';
}
}
function showCart() {
$currency = 'UGX';
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$output[] = '<table class="table table-striped">';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE product_id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Remove</td>';
$output[] = '<td>'.$product_name.'</td>';
$output[] = '<td>'.$currency.''.$product_price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>'.$currency.''.($product_price * $qty).'</td>';
$total += $product_price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: <strong>'.$currency.''.$total.'</strong></p>';
$output[] = '<div><button type="submit">Update cart</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
}
return join('',$output);
}
?>
This is my cart script that handles actions from the cart buttons(add, delete and update)
<?php
session_start();
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.!isset($_GET['product_id']);
} else {
$cart = !isset($_GET['product_id']);
}
break;
case 'delete':
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if (!isset($_GET['product_id']) != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
$cart = $newcart;
}
break;
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
if (stristr($key,'qty')) {
$id = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
for ($i=1;$i<=$value;$i++) {
if ($newcart != '') {
$newcart .= ','.$id;
} else {
$newcart = $id;
}
}
}
}
}
$cart = $newcart;
break;
}
$_SESSION['cart'] = $cart;
?>
And this is how send actions to my cart from the add button
<form action="cart.php?action=add&id=<?php echo $row_prdt_details['product_id']; ?>" method="post" id="cart">
<fieldset>
<address>
<strong>Name:</strong> <span><?php echo $row_prdt_details['product_name']; ?></span><br>
<strong>Cake Code:</strong> <span><?php echo $row_prdt_details['product_id']; ?></span><br>
<strong>Availability:</strong> <span>
</span><br>
</address>
<h4><strong>Price: UGX <?php echo $row_prdt_details['product_price']; ?></strong></h4>
<p> </p>
<label>Qty:</label>
<input type="text" class="span1" name="qty" placeholder="1">
<input type="submit" onClick="window.location.reload()" />
</fieldset>
</form>
All i want to achieve is to be able to add more items
Any help is greatly welcomed, if u have any questions about what am doing please ask me

id is not defined in my shopping cart

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

How to unset / destroy session that retrieves data from mysql

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']) {
....

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(:

Categories