Diether Posted December 27, 2012 Share Posted December 27, 2012 hi guys..This codes really works fine to me but as a student i want to know how it works. PLease see my problem below. <?php ob_start(); session_start(); // Start session first thing in script // Script Error Reporting error_reporting(E_ALL); ini_set('display_errors', '1'); ?> <?php // Connect to the MySQL database require_once("includes/connection.php"); ?> <?php include("includes/header.php"); ?> <?php // // 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(); } ?> <?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 } ?> <?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"]); } } ?> <?php // // 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="you@youremail.com">'; // 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 product WHERE id='$item_id' LIMIT 1"); while ($row = mysql_fetch_array($sql)) { $product_name = $row["name"]; $price = $row["price"]; $details = $row["details"]; } $pricetotal = $price * $each_item['quantity']; $cartTotal = $pricetotal + $cartTotal; setlocale(LC_MONETARY, "en_US"); $pricetotal = number_format($pricetotal,2); // 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>"; $cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><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><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></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>'; $i++; } setlocale(LC_MONETARY, "en_US"); $cartTotal = number_format($cartTotal,2); $cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." Php</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.yoursite.com/storescripts/my_ipn.php"> <input type="hidden" name="return" value="https://www.yoursite.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="https://www.yoursite.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>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Your Cart</title> <link rel="stylesheet" href="style/style.css" type="text/css" media="screen" /> </head> <body> <a href = "index.php">Continue shopping </a> <div align="center" id="mainWrapper"> <div id="pageContent"> <div style="margin:24px; text-align:left;"> <br /> <table width="100%" border="1" cellspacing="0" cellpadding="6"> <tr> <td width="18%" bgcolor="#C5DFFA"><strong>Product</strong></td> <td width="45%" bgcolor="#C5DFFA"><strong>Product Description</strong></td> <td width="10%" bgcolor="#C5DFFA"><strong>Unit Price</strong></td> <td width="9%" bgcolor="#C5DFFA"><strong>Quantity</strong></td> <td width="9%" bgcolor="#C5DFFA"><strong>Total</strong></td> <td width="9%" bgcolor="#C5DFFA"><strong>Remove</strong></td> </tr> <?php echo $cartOutput; ?> <!-- <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> --> </table> <?php echo $cartTotal; ?> <br /> <br /> <?php //echo $pp_checkout_btn; ?> <br /> <br /> <a href="cart.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a> </div> <br /> </div> </div> </body> <?php include("includes/footer.php"); ob_flush(); ?> </html> This is the part that i can't understand clearly. Can someone help me to explain about this line of codes? and how can i grab the value of this array to be more readable so that i can clearly understand what is happening with this process. This is would be a big help for my study. Thanks in advance. // 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 Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/ Share on other sites More sharing options...
Muddy_Funster Posted December 27, 2012 Share Posted December 27, 2012 all that bit of code does is, each time an item is added to the cart, steps through everything that is already in the cart, and if that item has already been put into the cart updates the quantity rather than adding a whole new item line. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401474 Share on other sites More sharing options...
Diether Posted December 27, 2012 Author Share Posted December 27, 2012 thank you muddy_funster, in addition ,Do you know how to grab the values of that array for testing to make it more readable? just like this. print_r($array); Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401481 Share on other sites More sharing options...
trq Posted December 27, 2012 Share Posted December 27, 2012 print_r([color=#000000][size=2]$_SESSION[/size][/color][color=#666600][size=2][[/size][/color][color=#008800][size=2]"cart_array"[/size][/color][color=#666600][size=2]]);[/[code=php:0][/size][/color] Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401485 Share on other sites More sharing options...
Diether Posted December 27, 2012 Author Share Posted December 27, 2012 thanks trq , it really helps. can i simplify this line of codes? Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401490 Share on other sites More sharing options...
Muddy_Funster Posted December 27, 2012 Share Posted December 27, 2012 It doesn't really get any simpler than what trq posted. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401501 Share on other sites More sharing options...
Diether Posted December 27, 2012 Author Share Posted December 27, 2012 // 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 i mean this one? can it be simplified? thanks Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401506 Share on other sites More sharing options...
Muddy_Funster Posted December 27, 2012 Share Posted December 27, 2012 As a general rule of thumb, if you don't understand it, don't mess with it. It's already only 6 lines of pretty simple code, why would you want to alter it? Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401511 Share on other sites More sharing options...
Christian F. Posted December 27, 2012 Share Posted December 27, 2012 You can replace the while (list () = each ()) loop with a foreach (), as it does exactly what the foreach () would do. Only less efficient. In fact, I'd do away with that inner loop completely, and just check on the keys directly. No need for either it nor the array_splice () from what I can see. If there's no need for it, then it shouldn't be there. See my sig. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401527 Share on other sites More sharing options...
PFMaBiSmAd Posted December 27, 2012 Share Posted December 27, 2012 (edited) Can that code be simplified, yes, greatly. If the cart array index is changed so that it is the item_id - $_SESSION['cart_array'][$pid] = array(....); all the code for adding, removing, and getting the details for the items, can be greatly simplified - if (isset($_POST['pid'])) { // add (+1) item to cart $pid = (int)$_POST['pid']; // cast as integer // valid pids are > 0 if($pid > 0){ if(!isset($_SESSION['cart_array'][$pid])){ // item is not in the cart, add it with quantity = 1 $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index } else { // item is in the cart, increment quantity $_SESSION['cart_array'][$pid]['quantity']++; } } header("location: cart.php"); exit(); } To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once. Edited December 27, 2012 by PFMaBiSmAd Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401533 Share on other sites More sharing options...
Diether Posted December 27, 2012 Author Share Posted December 27, 2012 Can that code be simplified, yes, greatly. If the cart array index is changed so that it is the item_id - $_SESSION['cart_array'][$pid] = array(....); all the code for adding, removing, and getting the details for the items, can be greatly simplified - if (isset($_POST['pid'])) { // add (+1) item to cart $pid = (int)$_POST['pid']; // cast as integer // valid pids are > 0 if($pid > 0){ if(!isset($_SESSION['cart_array'][$pid])){ // item is not in the cart, add it with quantity = 1 $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index } else { // item is in the cart, increment quantity $_SESSION['cart_array'][$pid]['quantity']++; } } header("location: cart.php"); exit(); } To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once. thanks PFMaBismad ,, i will try this.. i think this is more easier to understand..i will leave comment here if it works. thanks also to Christian F for your comment. have a nice day to everyone Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401538 Share on other sites More sharing options...
PFMaBiSmAd Posted December 27, 2012 Share Posted December 27, 2012 Changing the array index to be the item_id will also have the benefit of making your 'remove from cart' code so that it won't keep removing other items if you refresh the page. You should always act upon data items by their specific id/identifier, not by their position in a list/array. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401540 Share on other sites More sharing options...
Diether Posted December 28, 2012 Author Share Posted December 28, 2012 @ PFMaBismAd , your codes works perfectly. thank you so much. i take down notes also so that i can study the logic. Can you also help me to simplify this line. <?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 } what i did is this.. but it does not adjust my items in the cart. if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != ""){ $item_to_adjust =(int) $_POST['item_to_adjust']; if($item_to_adjust > 0){ if(!isset($_SESSION['cart_array'][$pid])){ //item is in tht cart so add it with 1 $_SESSION['cart_array'][$item_to_adjust] = array("item_id" => $pid, "quantity" =>1); }else{ //item is in the cart, increment quantity $_SESSION['cart_array'][$item_to_adjust]['quantity']++; } } header("location : cart.php"); exit(); } Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401723 Share on other sites More sharing options...
Christian F. Posted December 28, 2012 Share Posted December 28, 2012 This test && $_POST['item_to_adjust'] != "" is actually somewhat useless, as you have a more specific test (> 0) later on. Also, the code you posted is an exact copy of what MaBi posted above: It's meant to increment the item quantity by 1, not let the user adjust the quantity manually. For that you need to retrieve the value of $_POST['quantity'], typecast it, and then set the quantity of the item to the retrieved value. If you do not want the user to only be able to adjust items he already has in the cart, then you can also leave out the check for the item ID in the cart array. PS: Also, in your original code this check will never be evaluated to true: if ($quantity == "") { $quantity = 1; } The line above checks for $quantity less than 1, which an empty string is. So by the time the parser gets to this line, $quantity will always be set to a number between 1 and 99 inclusive. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401811 Share on other sites More sharing options...
Diether Posted December 28, 2012 Author Share Posted December 28, 2012 This test && $_POST['item_to_adjust'] != "" is actually somewhat useless, as you have a more specific test (> 0) later on. Also, the code you posted is an exact copy of what MaBi posted above: It's meant to increment the item quantity by 1, not let the user adjust the quantity manually. For that you need to retrieve the value of $_POST['quantity'], typecast it, and then set the quantity of the item to the retrieved value. If you do not want the user to only be able to adjust items he already has in the cart, then you can also leave out the check for the item ID in the cart array. PS: Also, in your original code this check will never be evaluated to true: if ($quantity == "") { $quantity = 1; } The line above checks for $quantity less than 1, which an empty string is. So by the time the parser gets to this line, $quantity will always be set to a number between 1 and 99 inclusive. hi ChristianF, can you help me build the code for that so that i can study the logic behind? Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401816 Share on other sites More sharing options...
Christian F. Posted December 28, 2012 Share Posted December 28, 2012 The logic behind it is already typed out in my post. Set it up in a step-by-step list, and you'll get this: if ItemAdjust - Cast item ID to int. - Cast item quantity to int. - Set quantity for item ID. - Redirect and kill script Do whatever else. As my sig says: Keep it simple. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401829 Share on other sites More sharing options...
Diether Posted December 28, 2012 Author Share Posted December 28, 2012 The logic behind it is already typed out in my post. Set it up in a step-by-step list, and you'll get this: if ItemAdjust - Cast item ID to int. - Cast item quantity to int. - Set quantity for item ID. - Redirect and kill script Do whatever else. As my sig says: Keep it simple. i will try this.. then i will leave comment later if i got the right answer. thanks anyway, Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401831 Share on other sites More sharing options...
Love2c0de Posted December 28, 2012 Share Posted December 28, 2012 thank you muddy_funster, in addition ,Do you know how to grab the values of that array for testing to make it more readable? just like this. To make your array more readable, you can print it like this: echo "<pre>"; print_r($array); echo "</pre>"; Regards, AoTb. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401832 Share on other sites More sharing options...
Diether Posted December 28, 2012 Author Share Posted December 28, 2012 To make your array more readable, you can print it like this: echo "<pre>"; print_r($array); echo "</pre>"; Regards, AoTb. thanks men. Can you help to solve my problem on how to simplify this line ? <?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 } ?> Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401838 Share on other sites More sharing options...
Love2c0de Posted December 28, 2012 Share Posted December 28, 2012 thanks men. Can you help to solve my problem on how to simplify this line ? I wish I knew how to but I think you got some very talented coders helping you here, so you should really stick with their advice! I'm quite new to php so I'm not in a position to help when it comes to more advanced stuff. Regards, AoTB. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401842 Share on other sites More sharing options...
Diether Posted December 28, 2012 Author Share Posted December 28, 2012 if (isset($_POST['item_to_adjust']) { $item_to_adjust =(int) $_POST['item_to_adjust']; ////////////////////////////////// // some codes to adjust the cart// ////////////////////////////////// header("location : cart.php"); //kill the script exit(); } ChristianF.. Am I in the right track now? my problem now is the code that would adjust the cart? i wish i can make this work. regards Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401844 Share on other sites More sharing options...
Christian F. Posted December 28, 2012 Share Posted December 28, 2012 Just keep going, and you'll soon find out if you're on the right track or not. Quote Link to comment https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/#findComment-1401847 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.