susanwiese Posted August 2, 2015 Share Posted August 2, 2015 Hello everyone, Let me first say that I am a PHP beginner. With the use of online video tutorials I have setup a shopping cart for my online store that sells stainless steel jewelry. Everything is working well, but I want to add something and even though I know what needs to e done - I don't know how to go about it. Can someone please help me out? So I have a product page that gets the product's name, code, price and details from the database. This is the page's code: <?php // Script Error Reporting error_reporting(E_ALL); ini_set('display_errors', '1'); ?> <?php // Check to see the URL variable is set and that it exists in the database if (isset($_GET['id'])) { // Connect to the MySQL database include "storescripts/connect_to_mysql.php"; $id = preg_replace('#[^0-9]#i', '', $_GET['id']); // Use this var to check to see if this ID exists, if yes then get the product // details, if no then exit this script and give message why $sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); $productCount = mysql_num_rows($sql); // count the output amount if ($productCount > 0) { // get all the product details while($row = mysql_fetch_array($sql)){ $product_code = $row["product_code"]; $product_name = $row["product_name"]; $price = $row["price"]; $details = $row["details"]; $category = $row["category"]; $date_added = strftime("%b %d, %Y", strtotime($row["date_added"])); } } else { echo "The item does not exist."; exit(); } } else { echo "Data to render this page is missing."; exit(); } mysql_close(); ?> <!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> <title><?php echo $product_code; ?></title> <meta http-equiv="Content-type" content="text/html; charset=us-ascii" /> <meta http-equiv="Content-Language" content="en-us" /> <meta http-equiv="imagetoolbar" content="no" /> <meta name="MSSmartTagsPreventParsing" content="true" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="Susan Wiese" /> <link rel="stylesheet" href="css/style.css" type="text/css" /> </head> <body> <div id="page-container"> <div id="header"> <?php include "storescripts/header.php"; ?> </div> <div id="center-panel"> <div class="box1"> <?php include "storescripts/menu.php"; ?> </div> <div class="box1"> <table width="100%" border="0" cellspacing="0" cellpadding="15" align="center"> <tr> <td width="25%" valign="top"> <img src="inventory_images/<?php echo $id; ?>.jpg" width="200" height="200" alt="<?php echo $product_name; ?>" /><br /> <a href="inventory_images/<?php echo $id; ?>.jpg">View full size</a></td> <td width="75%" valign="top"> <h3><?php echo $product_code; ?></h3> <?php echo $product_name; ?><br /> <br /> <?php echo $details; ?><br /> <br /> <?php echo "R".$price; ?><br /> <br /> <form id="form1" name="form1" method="post" action="cart.php"> <label for="engraving">Engraving</label><br /> <input type="text" name="engraving" id="engraving" size="35" /><br /> <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /><br /> <input type="submit" name="button" id="button" class="submit" value="Add to cart" /> </form> </td> </tr> </table> </div> <div class="box1"> <?php include "storescripts/order.php"; ?> </div> </div> <div id="footer"> <?php include "storescripts/footer.php"; ?> </div> </div> </body> </html> The product page looks like this: http://www.personalizedjewellery.co.za/store/product.php?id=3 You'll notice I've added an "Engraving" label to the form. I want a visitor to be able to add the engraving they want to be done on this product. This information should then be sent to the cart with all the other details when the person adds the item to their cart. I want the text to be engraved to be displayed in the cart's table with the image, price, etc. This output should be in the//Create the product array section of cart.php (where I have added $engraving) Cart.php <?php session_start(); // Start session first thing in script // Script Error Reporting error_reporting(E_ALL); ini_set('display_errors', '1'); // Connect to the MySQL database include "storescripts/connect_to_mysql.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 = "<h3 align='center'>Your shopping cart is empty</h3>"; } else { // 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_code = $row["product_code"]; $product_name = $row["product_name"]; $price = $row["price"]; } $pricetotal = $price * $each_item['quantity']; $cartTotal = $pricetotal + $cartTotal; $pricetotal = money_format("%.2n", $pricetotal); // 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_code . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_code. '" width="75" height="75" border="1" /></td>'; $cartOutput .= '<td>R' . $engraving . '</td>'; $cartOutput .= '<td>R' . $price . '</td>'; $cartOutput .= '<td><form action="cart.php" method="post"> <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" /><br /> <br /> <input name="adjustBtn' . $item_id . '" type="submit" class="submit" value="Change" /> <input name="item_to_adjust" type="hidden" value="' . $item_id . '" /> </form></td>'; //$cartOutput .= '<td>' . $each_item['quantity'] . '</td>'; $cartOutput .= '<td>R' . $pricetotal . '</td>'; $cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" class="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>'; $cartOutput .= '</tr>'; $i++; } $cartTotal = money_format("%.2n", $cartTotal); $cartTotal = "R".$cartTotal." "; } ?> <!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> <title>Your Cart</title> <link rel="stylesheet" href="css/style.css" type="text/css" /> </head> <body> <?php include_once("storescripts/analyticstracking.php") ?> <div id="page-container"> <div id="header"> <?php include "storescripts/header.php"; ?> </div> <div id="center-panel"> <div class="box1"> <?php include "storescripts/menu.php"; ?> </div> <div class="box1"> <center> <img src="images/cart.png" alt="Cart" title="Cart" border="0" /> <h3>Your Cart</h3> </center> <div style="margin:24px; text-align:left;"> <table width="80%" border="1" cellspacing="0" cellpadding="6" align="center"> <tr> <td width="20%" bgcolor="#FFFFFF"><strong>Product</strong></td> <td width="35%" bgcolor="#FFFFFF"><strong>Engraving</strong></td> <td width="10%" bgcolor="#FFFFFF"><strong>Price</strong></td> <td width="10%" bgcolor="#FFFFFF"><strong>Quantity</strong></td> <td width="10%" bgcolor="#FFFFFF"><strong>Total</strong></td> <td width="10%" bgcolor="#FFFFFF"><strong>Remove</strong></td> </tr> <?php echo $cartOutput; ?> </table> <br /> Cart Total: <?php echo $cartTotal; ?> | <a href="cart.php?cmd=emptycart">Empty your cart</a><br /> <br /> <h3>If you buy 6 items, you will receive the 6th item for free</h3> This adjustment will be made on your invoice before we send it to you.<br /> <br /> <h3>Postage</h3> The postage cost is to be added to the total above.<br /> • Post Office Registered Mail: R50<br /> • Fastway Couriers (Limited Service): R55<br /> • Speed Services: R90<br /> • Aramex Couriers (Full Service): R105<br /> </div> </div> </div> <div id="footer"> <?php include "storescripts/footer.php"; ?> </div> </div> </body> </html> Could someone please help me get the text to be engraved added to the cart? I would really appreciate it. It is probably very simple, but I'm completely stuck. ThanksSusan Quote Link to comment https://forums.phpfreaks.com/topic/297599-please-help-me-add-some-code-for-my-shopping-cart/ Share on other sites More sharing options...
Barand Posted August 2, 2015 Share Posted August 2, 2015 Instead of looping through the session array to see if pid already exists, why don't you make pid the key to the array element. Saves all that array searching and splicing eg <?php // check if in array if (isset($_SESSION['cart'][$pid])) { // it exists so increment the qty $_SESSION['cart'][$pid]['qty']++; } else { // add to cart $_SESSION['cart'][$pid] = array ('qty' => 1, 'engraving' => $engraving); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/297599-please-help-me-add-some-code-for-my-shopping-cart/#findComment-1517907 Share on other sites More sharing options...
susanwiese Posted August 2, 2015 Author Share Posted August 2, 2015 Thank you Barand. I got this code from a video tutorial and it works very well. I just want to know how to get the engraving input from the products page to be added to the cart. I'm stuck with that. Quote Link to comment https://forums.phpfreaks.com/topic/297599-please-help-me-add-some-code-for-my-shopping-cart/#findComment-1517908 Share on other sites More sharing options...
mac_gyver Posted August 2, 2015 Share Posted August 2, 2015 the tutorial you are following has 2-3 times too much code because the design of the cart is not efficient. it's also running a database query inside of a loop, which is killing your database server with queries. the code example that Barand posted does show you how to add the engraving input to the cart. you can modify his code to work with your cart definition or it would be better to modify your cart definition to match what he suggested. your current "add to cart" code is about 20-30 lines of code. most of that would be replaced with the few lines that he posted. you would still need to detect if $_POST['pid'] is set and cast/validate the pid value (which your current code isn't even doing) and validate the engraving value. similarity, all the other code blocks, except for the 'empty cart', can be simplified to just a few lines of code, if you simplify the definition of the cart. for the code that's retrieving and displaying the product information from the database, with the simplified cart definition, use array_keys() to get all the product id's at once, implode() that to make a comma separated list, then use that in ONE database query, using an IN() comparison in the WHERE clause to retrieve all the product information at once. you can then loop over the rows retrieved from the database and display the contents of the cart. you would use the id from the database rows to reference the quantity and engraving values stored in the cart. Quote Link to comment https://forums.phpfreaks.com/topic/297599-please-help-me-add-some-code-for-my-shopping-cart/#findComment-1517913 Share on other sites More sharing options...
mac_gyver Posted August 2, 2015 Share Posted August 2, 2015 here's a point to ponder. if you allow multiple of any one item to be added to your cart, which you should, make sure that you provide a way of allowing the same or different engraving on each of those same items. you may want to make the entry of the engraving a separate step, where you display all the engrave-able items and allow entry of the engraving for each one. Quote Link to comment https://forums.phpfreaks.com/topic/297599-please-help-me-add-some-code-for-my-shopping-cart/#findComment-1517915 Share on other sites More sharing options...
susanwiese Posted August 3, 2015 Author Share Posted August 3, 2015 Thank you both very much - I appreciate your input. Kind regards, Susan Quote Link to comment https://forums.phpfreaks.com/topic/297599-please-help-me-add-some-code-for-my-shopping-cart/#findComment-1517919 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.