3cool4school Posted May 12, 2012 Share Posted May 12, 2012 Hello everyone I have coded a php cart for my website. I coded one myself instead of using a big box because it is a membership based sites where users use credits to order not cash. I have a 'Sizes' table with (size_id and size_name) and a 'Sizes_List' table with (size_id and product_id) which stores the size options of each product. It is displayed fine on the product page. Anyhoo. It works great.. there aren't any actual errors in the code but I am having trouble with 3 things.. 1. displaying the product size [i grab it in $_POST and add it to the cart_array) but it doesn't show up. 2. If I add another product, but a different size, to the cart it just changes the quantity of the product but doesn't add a new line. 3. I need to put items on "hold" for a certain amount of time (e.g. if you add a pair of True Religions in size 32 to your cart they are no longer available to anybody for 20 minutes and if you don't checkout they are back in the store). For the purpose of this question I have removed the need to be logged in for 1 product page and the cart. http://www.theskinnyminnie.com/user/rent/product.php?id=4/ <<product http://www.theskinnyminnie.com/user/mybox.php <<cart Here is the code it POST the values to the cart (if user adds to cart) <div id="addproduct"><form id="form1" name="form1" method="post" action="../mybox.php"> <div id ="size">Size: <select name="size"> <?php echo $the_sizes;?> </select></div> <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /> <input type="submit" name="button" id="button" value="Add to Box" /> </form></div> Here is the code for the cart User adds to cart: <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 1 (if user attempts to add something to the cart from the product page) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (!empty($_POST['form1'])) { $pid = $_POST['pid']; $asizeid = $_POST['size']; echo $asizeid; $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, "asize_id" => $asizeid)); } 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, "asize_id" => $asizeid))); $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, "asize_id" => $asizeid)); } } header("location: mybox.php"); exit(); } ?> User empties shopping car <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 2 (if user chooses to empty their shopping cart) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") { unset($_SESSION["cart_array"]); } ?> <?php adjust item quantity <?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, "asize_id" => $asizeid))); } // close if condition } // close while loop } // close foreach loop } ?> remove item <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 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"]); } } ?> View Cart - Ignore $orderSummary it is for the checkout process .. <?php ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Section 5 (render the cart for the user to view on the page) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $cartOutput = ""; $itemtotal = ""; $cartTotal = ""; $orderTotal = ""; $pp_checkout_btn = ''; $product_id_array = ''; if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { $itemtotal = "0"; $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2><br />"; } else { $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $item_id = $each_item['item_id']; $sql = mysql_query("SELECT * FROM Products WHERE product_id='$item_id' LIMIT 1"); while ($row = mysql_fetch_array($sql)) { $product_brand = $row["product_brand"]; $product_style = $row["product_style"]; $credits = $row["credits"]; $details = $row["details"]; } $sql4 = mysql_query("SELECT * FROM Sizes WHERE size_id = '$asize_id'"); while($name3 = mysql_fetch_array($sql4)){$product_size = $name3['size_name'];} $creditstotal = $credits * $each_item['quantity']; $cartTotal = $creditstotal + $cartTotal; $orderTotal = $creditstotal + $orderTotal; $itemtotal += $each_item['quantity']; $orderItem_qty = $each_item["quantity"]; $orderItem_total += $each_item["quantity"]; $orderSummary .= "<tr>"; $orderSummary .= "<td>"; $orderSummary .= "<div class = 'an_order_item'>"; $orderSummary .= "<img class ='an_order_img' src = 'inventory_images/".$item_id.".jpg' />"; $orderSummary .= "<div class = 'an_order_box'>"; $orderSummary .= "<div class = 'an_order_title'>"; $orderSummary .= "<h1>".$product_brand." - <font color='black'>".$product_style. "</font></h1>"; $orderSummary .= "</div>"; $orderSummary .= "<div class = 'an_order_size'>"; $orderSummary .= "<h1>Size - ".$product_size."</h1>"; $orderSummary .= "</div>"; $orderSummary .= "<div class = 'an_ordercalc'>"; $orderSummary .= "<h1>".$orderItem_qty." x ".$credits."pts = ".$creditstotal."pts</h1>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</div>"; $orderSummary .= "</td>"; $orderSummary .= "</tr>"; $orderSummary2 .= "<tr>"; $orderSummary2 .= "<td>"; $orderSummary2 .= "<div class = 'an_order_item'>"; $orderSummary2 .= "<img class ='an_order_img' src = 'rent/inventory_images/".$item_id.".jpg' />"; $orderSummary2 .= "<div class = 'an_order_box'>"; $orderSummary2 .= "<div class = 'an_order_title'>"; $orderSummary2 .= "<h1>".$product_brand."</h1>"; $orderSummary2 .= "<h1><font color='black'>".$product_style. "</font></h1>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</div>"; $orderSummary2 .= "</td>"; $orderSummary2 .= "</tr>"; $x = $i + 1; $product_id_array .= "$item_id-".$each_item['quantity'].","; // Dynamic table row assembly $cartOutput .= "<tr>"; $cartOutput .= $sizeid; $cartOutput .= '<td class="img"><a href="rent/product.php?id=' . $item_id . '"><img src="rent/inventory_images/' . $item_id . '.jpg" alt="' . $product_brand. '" height="121px" border="1" /></a><br /></td>'; $cartOutput .= '<td class="desc"> <strong><a href="rent/product.php?id=' . $item_id . '">' . $product_brand."-".$product_style . '</a></strong><ul class="attributes"><li>'. $details .'</li></ul><p class="size">Size - '.$product_size.'</p></td>'; $cartOutput .= '<td class="price">' . $credits .' <font id="pts">PTS</font></td>'; $cartOutput .= '<td class="qty"><form action="mybox.php" method="post"> <input name="quantity" type="number" value="' . $each_item['quantity'] . '" size="1" maxlength="2" /> <input class="change" name="adjustBtn' . $item_id . '" type="submit" value="Update" /> <input name="item_to_adjust" type="hidden" value="' . $item_id . '" /> </form> <form action="mybox.php" method="post"><input class="delete" name="deleteBtn' . $item_id . '" type="submit" value="Remove" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form> </td>'; //$cartOutput .= '<td>' . $each_item['quantity'] . '</td>'; $cartOutput .= '<td class="total">' . $creditstotal .'</td>'; $cartOutput .= '</tr>'; $i++; } setlocale(LC_MONETARY, "en_US"); //$cartTotal = $cartTotal.''; $cartTotal = '<tr><td colspan="4">Total</td><td class="total cart-total-price">' . $cartTotal .'</td></tr>'; // Finish the Paypal Checkout Btn } ?> Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/ Share on other sites More sharing options...
PFMaBiSmAd Posted May 12, 2012 Share Posted May 12, 2012 Your items #1, and #2 don't work because your code isn't testing and using the asize_id value(s) as a key to find the data in the cart. Your current code also isn't able to maintain different asize_id records under each item_id. For your current scheme, of having one item_id that can have different asize_id values, instead of treating different variations of an item as different item_ids, you need to restructure the cart to use the asize_id value as an array key (I would use a zero value/array key to indicate no size information. Actual asize_id's would start at 1.) You also need to use the item_id as the key for the main cart_array. This will greatly simplify your code. Once you change your array structure, you will end up with something like - $_SESSION["cart_array"][item_id][asize_id] = quantity. This would end up looking like - $_SESSION["cart_array"][123][0] = 1; // quantity 1 of item_id 123, no asize_id $_SESSION["cart_array"][456][1] = 1; // quantity 1 of item_id 456, asize_id 1 $_SESSION["cart_array"][456][3] = 2; // quantity 2 of item_id 456, asize_id 3 The reason this will greatly simplify your code is you can test/set array values by directly referencing array elements. Your posted add to cart code would become - <?php if (!empty($_POST['form1'])) { $pid = $_POST['pid']; $asizeid = $_POST['size']; if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { $_SESSION["cart_array"] = array(); // create empty cart } if(!isset($_SESSION['cart_array'][$pid][$asizeid])){ // item is not in the cart $_SESSION['cart_array'][$pid][$asizeid] = 0; // create empty item } $_SESSION['cart_array'][$pid][$asizeid]++; // add 1 to the quantity header("location: mybox.php"); exit(); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/#findComment-1344988 Share on other sites More sharing options...
3cool4school Posted May 12, 2012 Author Share Posted May 12, 2012 Thanks so much! .. That makes so much sense and simplifies the code down so much. But would I still need $each_item? and foreach ($_SESSION["cart_array"] as $each_item) ? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/#findComment-1344991 Share on other sites More sharing options...
PFMaBiSmAd Posted May 12, 2012 Share Posted May 12, 2012 The only place you would loop over anything would be in the view cart code, and even there, the only thing you would loop over is the data a (one) query returns. To get the product information for the items in the cart, you would get the cart's main array keys (item_ids) and use an IN () term in your query. <?php $ids = implode(',',array_keys($_SESSION['cart_array'])); $query = "SELECT * FROM Products WHERE product_id IN ($ids)"; The above query will get ALL the product information for ALL the items in the cart at one time. You would just loop over that result set to output the contents of the cart. Edit: As you loop through this result set, to get and display the quantity for each size, you would simply access and loop over $_SESSION['cart_array'][current_item_id_variable_here...], which will be an array of the asize_id keys and quantity. Edit2: To avoid putting the query for the `Sizes`table inside of a loop, you either need to learn to use Join statements in your queries or query for all the `Sizes` data and put it into an array with the asize_id as the key, before you loop of the main result set. Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/#findComment-1344993 Share on other sites More sharing options...
3cool4school Posted May 13, 2012 Author Share Posted May 13, 2012 Thanks for the help! you have been awesome!! .. I have a problem I got the first part to work, and when I add products to the cart they are in the array. but when I implode them and rip them apart in the for loop it doesn't work.. if I echo $ids by itself i get the proper array e.g. 10,12,15 . but the count($ids) says there is 1 number . and in the for loop I echo'd to check and all i got was Piece 0 = 1 . this is what I have before the cart outputs. $ids = implode(',',array_keys($_SESSION['cart_array'])); $query = "SELECT * FROM Products WHERE product_id IN ($ids)"; for($i = 0; $i< count($ids); $i++){ $item_id = $ids[$i]; echo "Piece #$i = $ids[$i] <br />"; } $sql = mysql_query($query); while ($row = mysql_fetch_array($sql)) { $product_brand = $row["product_brand"]; $product_style = $row["product_style"]; $credits = $row["credits"]; $details = $row["details"]; $sql4 = mysql_query("SELECT * FROM Sizes WHERE size_id = '$asizeid'"); while($name3 = mysql_fetch_array($sql4)){$product_size = $name3['size_name'];} } Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/#findComment-1345071 Share on other sites More sharing options...
PFMaBiSmAd Posted May 13, 2012 Share Posted May 13, 2012 As you loop over the result set from that query, to access the size/quantity in the cart, see the following sample logic - <?php $ids = implode(',',array_keys($_SESSION['cart_array'])); $query = "SELECT * FROM Products WHERE product_id IN ($ids)"; $result = mysql_query($query); while($row = mysql_fetch_assoc($result)){ // do what ever you want with the product_brand, product_style, credits, details ... // loop over the cart entries for the current product_id foreach($_SESSION['cart_array'][$row['product_id']] as $asize_id => $quantity){ if($asize_id == 0){ // there is no size associated with this entry echo "Quantity: $quantity<br />"; } else { // there is a size associated with this entry // associate the $asize_id with the actual size information using your favorite method (my post above suggest two ways that would avoid putting a query inside this loop) echo "Size(id - get the actual size info anyway you want...): $asize_id, Quantity: $quantity<br />"; } } } Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/#findComment-1345130 Share on other sites More sharing options...
3cool4school Posted May 13, 2012 Author Share Posted May 13, 2012 I got it to work! .. Thanks so much!! you are such a help!!! Quote Link to comment https://forums.phpfreaks.com/topic/262443-php-cart-help/#findComment-1345153 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.