Jump to content

When i add to cart, cart shows empty. but if i reload page, the items are in cart


etikem

Recommended Posts

Hi there,

I am trying to figure out what went wrong. something very strange happened.

 

When i click Add to Cart on the product page,

the cart.php opens but it tells me that the Cart is Empty.

 

If i hit F5 (refresh) it still tells me "Cart is empty".

BUT when i click on the Cart Link on my menu, the page reloads and show me all my products in the cart.

 

If i have 3 unique items in cart, when i try to delete only the first one, it tells me "Cart is empty"

When i try to delete the 2nd or 3rd, it tells me "Cart is empty" AND i get this error message:

Notice: Undefined index: cart_array in /home/_______/public_html/cart.php on line 76

 

And when i reload the page again, all the items are still in the cart.

 

I am so confused.

 

these is the code i have in cart.php  :

 

<?php 
session_start(); // Start session first thing in script
include "storescripts/connect_to_mysql.php"; 
 
error_reporting(E_ALL);
ini_set('display_errors', '1');
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//       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));
  }
}
    exit();
}
?>
<?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 (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 ($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 = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
// Start PayPal Checkout Button
$pp_checkout_btn .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="upload" value="1">
    <input type="hidden" name="business" value="HIDDEN">';
// Start the For Each loop
$i = 0; 
    foreach ($_SESSION["cart_array"] as $each_item) { 
$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"];
$description = $row["description"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
setlocale(LC_MONETARY, "en_US");
        $pricetotal = money_format("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$x = $i + 1;
$pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
        <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
        <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">  ';
// Create the product array variable
$product_id_array .= "$item_id-".$each_item['quantity'].","; 
 
// Dynamic table row assembly
$cartOutput .= '<tr class="cart_item">';
$cartOutput .= '<td class="product-remove"><form action="http://www._______.com/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 .= '<td class="product-thumbnail">
                                                <a href="http://www._______.com/product_detail.php?id=' . $item_id . '"><img width="145" height="145" alt="poster_1_up" class="shop_thumbnail" src="http://_______.com/inventory_images/'. $item_id .'.jpg"></a>
                                            </td>';
$cartOutput .= '<td class="product-name">
                                                <a href="http://www._______.com/product_detail.php?id=' . $item_id . '">' . $product_name . '</a> 
                                            </td>';
$cartOutput .= '<td class="product-price">
                                                <span class="amount">$' . $price . '</span> 
                                            </td>';
//$cartOutput .= '<td>' . $each_item['quantity'] . '</td>';
$cartOutput .= '<td><form action="http://www._______.com/cart.php" method="post">
<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
<input name="adjustBtn' . $item_id . '" type="submit" maxlength="2" value="Update" />
<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
</form></td>';
$cartOutput .= '<td class="product-subtotal">
                                                <span class="amount">' . $pricetotal . '</span> 
                                            </td>';
$cartOutput .= '</tr>';
$i++; 
    } 
setlocale(LC_MONETARY, "en_US");
    $cartTotal = money_format("%10.2n", $cartTotal);
$cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>".$cartTotal." USD</div>";
 
    // Finish the Paypal Checkout Btn
$pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
<input type="hidden" name="notify_url" value="https://www._______.com/storescripts/my_ipn.php">
<input type="hidden" name="return" value="http://www._______.com/checkout_complete.php">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cbt" value="Return to The Store">
<input type="hidden" name="cancel_return" value="http://www._______.com/paypal_cancel.php">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>';
}
 
?>
Link to comment
Share on other sites

most of the time, when it appears like you have multiple sessions that change depending on the method used to reach a page, it's because the host-name/sub-domain (the www. in the address) is changing depending on how you reach the page.
 
are the url's in the links and in the redirects constant and always have the www. as part of them?
 
as to any other problems in the code, you have far too much logic, due to an overly complicated data design. if you use the product id as the cart's array index and only store the quantity as the value in the array element, all the logic to manipulate the cart contents will be simplified. for example, here is what the add to cart logic would look like - 
 

// if the cart doesn't exist, create an empty one - you should put this logic in a common location above any code that references the cart
if(!isset($_SESSION['cart_array']))
{
    $_SESSION['cart_array'] = array();
}


// add a new item to cart with quantity 1, if already in cart add 1 to the quantity
if (isset($_POST['pid'])) {
     // pid is the product/item id
     $pid = (int)$_POST['pid']; // cast, or better yet validate, the value to php integer (will be limited to the operating system's maximum integer value)
     if(!isset($_SESSION['cart_array'][$pid]))
     {
         // if the item isn't in the cart, add it with quantity 0 (the quantity will be incremented to one in the next statement)
         $_SESSION['cart_array'][$pid] = 0;
     }
     // add 1 to the quantity
     $_SESSION['cart_array'][$pid]++;

     header("location: http://www._______.c...om/cart.php"); // you need to either set up a defined constant, a php variable, or use $_SERVER['HTTP_HOST'] to supply the hostname/domain for url's so that you don't need to type them in each instance throughout the code
     exit();
}

all other code will be equally simplified.
 
next, you should not run an sql query inside of a loop. to display the cart contents, just retrieve all the product id's (see array_keys() ), which will be either cast/validated as integers by your add to cart logic, form a comma separated list (see implode() ), and run one sql query with - WHERE id IN(the_comma_separated_list_goes_here) to get all the product data at one time. you can loop through the data from the query to display the cart, using the product id from each row to access the quantity value in the cart.
 
lastly, the php mysql extension is obsolete and was removed from php almost one year ago. you need to be learning current information or updating your code to use either the php PDO or msyqli extension. the PDO extension is more consistent and simpler to use over the mysqli extension.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.