PHP - Php Cart
Hello,
I got my hands in a php tutorial about creating a custom cart using only php. The thing is that, the code is working like that: 1. you see the items in the items.php page 2. you click on an item to open it in a new page and see full description 3. the add button is in the specific item's page and that's how the code works. Grabs the URL' s id variable and then get's processed. What I want: 1. To modify the code a little bit in order to have the add button into the into my items.php page so I skip the view full description link (I just don't like it as a requirement to add something to cart) But somewhere on my way there I got lost... Here are the codes (as they work in original script): For adding an item: Code: [Select] 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: ../p_cart.php"); exit(); }The check URL variable & the Add Button (both at the same page) the link of "View All Details" looks like this in order for this to work: <a href="specitem.php?id=1"> so it grubs the URL' s id and executes the code (something that I don't want) I want to take the id from my item form. Code: [Select] <?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_name = $row["product_name"]; $price = $row["price"]; $details = $row["details"]; $category = $row["category"]; $subcategory = $row["subcategory"]; $date_added = strftime("%b %d, %Y", strtotime($row["date_added"])); } } else { echo "That item does not exist."; exit(); } } else { echo "Data to render this page is missing."; exit(); } Code: [Select] <form id="form1" name="form1" method="post" action="cart.php"> <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /> <input type="submit" name="button" id="button" value="Add to Shopping Cart" /> </form> Similar TutorialsHow can I make index.php?view=cart work in place of cart.php in the following code? Works: header("Location: cart.php?msg=Thank you. Check your e-mail for Login details."); die; } else header("Location: cart.php?msg=Account with given email does not exist."); die; Doesn't work: header("Location: index.php?view=cart?msg=Thank you. Check your e-mail for Login details."); die; } else header("Location: index.php?view=cart?msg=Account with given email does not exist."); die; Hey again, Still on the same project but now doing the cart page. I've been bringing my skills up to date a lot doing this project, however, having said that I now can't figure out why my cart is not adding the items to the cart, i've checked the post data and the quantity is set to 1. Would really appreciate someone having a look at it and hopefully can see what i'm missing. you can see what it should look like (well so far lol) at here in my sandbox site. thanks again. (p.s. The parts are all over the place on the page, so thought better put whole page, sorry if shouldn't have done that) <?php // Initialize the session session_start(); // Include config file require_once "dbcontroller.php"; $db_handle = new DBController(); if(!empty($_GET["action"])) { switch($_GET["action"]) { case "add": if(!empty($_POST["quantity"])) { $productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_code='" . $_GET["product_code"] . "'"); $itemArray = array($productByCode[0]["product_code"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_code'=>$productByCode[0]["product_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["img1"])); if(!empty($_SESSION["cart_item"])) { if(in_array($productByCode[0]["product_code"],array_keys($_SESSION["cart_item"]))) { foreach($_SESSION["cart_item"] as $k => $v) { if($productByCode[0]["product_code"] == $k) { if(empty($_SESSION["cart_item"][$k]["quantity"])) { $_SESSION["cart_item"][$k]["quantity"] = 0; } $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"]; } } } else { $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); } } else { $_SESSION["cart_item"] = $itemArray; } } break; case "remove": if(!empty($_SESSION["cart_item"])) { foreach($_SESSION["cart_item"] as $k => $v) { if($_GET["product_code"] == $k) unset($_SESSION["cart_item"][$k]); if(empty($_SESSION["cart_item"])) unset($_SESSION["cart_item"]); } } break; case "empty": unset($_SESSION["cart_item"]); break; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>LeaversHoodies.ie</title> <!-- Bootstrap --> <link href="css/bootstrap-4.4.1.css" rel="stylesheet"> <link href="css/accordian.css" rel="stylesheet"> </head> <body> <?php include 'header_student.php'; ?> <br /> <?php $school_page = "ravenswell"; $sql = "SELECT * FROM schools WHERE school_page = '$school_page'"; if($result = mysqli_query($conn, $sql)) while($row = mysqli_fetch_array($result)) { ?> <h3 class="text-center">Student Ordering Page For</h3> <h2 class="text-center" style="text-transform:uppercase;"><?php echo $row['school_name']; ?></h2> <hr style="width: 50%; text-align:center; border: 2px solid #00aeef; border-radius: 5px; margin: 0 auto;"> <br /> <div class="container"> <div class="row"> <div class="col"> <?php $path = "images/schools/"; $file = $row["logo"]; if(!empty($row['logo'])) { echo '<img src="'.$path.$file.'" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } else { echo '<img src="images/schools/140x140.gif" style="width:95%; height:auto; margin-top:-130px;"><br /><br />'; } ?></div> <div class="col-6"> <h5>These are the garments your school has choosen :</h5><br /> <?php $school_id = $row["school_id"]; } var_dump($_SESSION); var_dump($_POST); $product_array = $db_handle->runQuery("SELECT * FROM choices INNER JOIN products USING (product_code) INNER JOIN colours USING (colour_id) WHERE school_id = '$school_id'"); if (!empty($product_array)) { foreach($product_array as $key=>$value){ ?> <div class="container"> <div class="row"> <div class="col-5" style="text-align:left;"> <img src="images/products/<?php echo $product_array[$key]["img1"]; ?>" alt="<?php echo $product_array[$key]["product_code"]; ?>" style="position:relative; top:0; width:200px; display:block;"> </div> <div class="col-7"> <h5><?php echo $product_array[$key]["product_name"]; ?></h5><p> in <?php echo $product_array[$key]["colour_name"]; ?></p> <p style="font-size:12px;"><?php echo $product_array[$key]["description"]; ?></p> <?php $comment = $product_array[$key]["comment"]; if (empty($comment)) { echo ""; } else { ?> <p style="font-size:12px;"><b>A note from your teacher:</b> <br /> <?php echo $product_array[$key]["comment"]; ?></p> <?php }; ?> <form action="student_order.php?schoolname=<?php echo $school_page; ?>?action=add&product_code=<?php echo $product_array[$key]["product_code"]; ?>" method="post"> <?php $product = $product_array[$key]["product_code"]; ?> Please select your size : <select id="size" name="size"> <?php $sql1 = "SELECT DISTINCT * FROM sizes WHERE product_code = '$product'"; if($result1 = mysqli_query($conn, $sql1)) while($row3 = mysqli_fetch_array($result1)){ echo "<option value='" . $row3['size'] . "'>" . $row3['size'] . "</option>"; } else { echo "nothing to see here"; } ?> </select> <br /><br /> <div class="number">How many do you want: <input type="number" style="font-size:12px;" id="quantity" name="quantity" value="1" min="1" max="5"><br /> Price : <?php echo "€".$product_array[$key]["price"]; ?> </div> <input type="hidden" id="product_code" value="<?php echo $product; ?>"><br /> <input type="submit" style="font-size:12px;" value="Add to Order" class="btnAddAction"> </form> </div> </div> <br /><hr style="width: 90%; text-align:center; border: 1px solid #00aeef; border-radius: 5px; margin: 0 auto;"><br /> </div> <?php } } else { echo "No Schools by that name registered."; } ?> </div> <div class="col-3"> <div style="border: 1px solid #d3d3d3; padding: 10px; border-radius: 5px; margin-top:30px;"> Your Order: </div> </div> </div> <div class="txt-heading">Shopping Cart</div> <a id="btnEmpty" href="student_order.php?schoolname=<?php echo $school_page; ?>?action=empty">Empty Cart</a> <?php if(isset($_SESSION["cart_item"])){ $total_quantity = 0; $total_price = 0; ?> <table class="tbl-cart" cellpadding="10" cellspacing="1"> <tbody> <tr> <th style="text-align:left;">Name</th> <th style="text-align:left;">Code</th> <th style="text-align:right;" width="5%">Quantity</th> <th style="text-align:right;" width="10%">Unit Price</th> <th style="text-align:right;" width="10%">Price</th> <th style="text-align:center;" width="5%">Remove</th> </tr> <?php foreach ($_SESSION["cart_item"] as $item){ $item_price = $item["quantity"]*$item["price"]; ?> <tr> <td><img src="images/products/<?php echo $item["img1"]; ?>" class="cart-item-image" /><?php echo $item["product_name"]; ?></td> <td><?php echo $item["product_code"]; ?></td> <td style="text-align:right;"><?php echo $item["quantity"]; ?></td> <td style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td> <td style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td> <td style="text-align:center;"><a href="student_order.php?schoolname=<?php echo $school_page; ?>?action=remove&product_code=<?php echo $item["product_code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td> </tr> <?php $total_quantity += $item["quantity"]; $total_price += ($item["price"]*$item["quantity"]); } ?> <tr> <td colspan="2" align="right">Total:</td> <td align="right"><?php echo $total_quantity; ?></td> <td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td> <td></td> </tr> </tbody> </table> <?php } else { ?> <div class="no-records">Your Cart is Empty</div> <?php } ?> </div> </div> <br /><br /> <?php include 'footer_student.php'; ?> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery-3.4.1.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/popper.min.js"></script> <script src="js/bootstrap-4.4.1.js"></script> </body> </html>
ok im making a shooping cart how do i make it so it remembers that items people add to the cart 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) Code: [Select] <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: Code: [Select] <?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 Code: [Select] <?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 Code: [Select] <?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 Code: [Select] <?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 .. Code: [Select] <?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 } ?> I'm not a programmer but can get buy a little with PHP. My need is a "Shopping Cart" and this is what I would like to see.
I have a MotoCMS web site and would like to but a shopping cart in one page all I need is a "Buy Now" button that can hold the "Item Name" "Price" and "Quantity" and Maybe a selectable option? And a "Cart" for my PayPal that I can put anywhere on the page. If I have to use a database that is OK.
I can put the product pictures and info on the page and then a Buy Now link button would be great.
Does anyone know of a shopping cart that I can use to do this?
Lon
Edited by Lon, 28 September 2014 - 09:07 PM. hi all i have a simple shopping cart up and runniing i just cannot think of how to remove all items within the cart i can do a remove one item easily but how woudl i remove all items inmy cart ? Would i delete the cookie id or ? To add items to my shopping cart the user must select a size and then click 'add to basket'. When they do this is adds the item and corresponding size to a string in this format 1s2 where 1 is the id and 2 is the size. Multiple items would look like this 1s2,2s1,1s2 That's all fine. The problem I am now having is getting the code to recognise 1s2 exists twice in the string and putting the $qty to 2 for that item. Here is my current code. Any help on this would be HUGELY appreciated as it's doing my head in! Thanks! Code: [Select] <div id="view_basket"> <ul> <?php $basket = $_SESSION['basket']; if ($basket) { $data = preg_split("#[s,]#", $basket); $data = array_chunk($data, 2); foreach($data as $key => $val) $contents[] = (isset($contents[$data])) ? $contents[$data] + 1 : 1; echo '<form action="basket.php?action=update" method="post">'; echo '<table>'; foreach ($data as $id=>$qty) { $sql = "SELECT * FROM store WHERE id LIKE '$id' AND live LIKE '0'"; $result = mysql_query($sql); while ($rows = mysql_fetch_array($result)) { extract($rows); ?> <li> <div id="view_basket_image"> <img src="<?php echo $rows['indeximage']; ?>" /> </div> <div id="view_basket_title"> <span class="view_basket_brand"><?php echo $rows['brand']; ?> ·</span> <span class="view_basket_description"><?php echo $rows['title']; ?></span> </div> <div id="view_basket_qty"> <input type="text" name="qty<?php echo $id; ?>" value="<?php echo $qty; ?>" size="3" maxlength="3" class="view_basket_qty" /> </div> <div id="view_basket_price"> <span class="view_basket_x">x</span>£<?php echo $rows['price']; ?> <?php /* WORK OUT ITEM WEIGHTS */ $itemweight = $rows['weight'] * $qty; $totalweight += $rows['weight'] * $qty; ?> </div> <div id="view_basket_itemtotal"> <?php $itemtotalprice = $rows['price'] * $qty; $itemtotal = number_format($itemtotalprice, 2, '.', ','); echo '£'; echo $itemtotal; $total += $rows['price'] * $qty; ?> </div> <div class="clear"></div> </li> <?php } } ?> </ul> </div> <?php } ?> Hi everyone, I am building a shopping cart for a group of friends' website. It is a pay-per-view workout website. Basically, they want to let people find workout videos and pay on a per-day basis (1 day, 3 days, 7 days and depending on the video pricing will be different). I have set them up everything except I am having some difficulty with the shopping cart. I took the basics of the shopping cart script from a tutorial I found online and then modified it. The only problem is that most shopping carts send an action and a product id through the URL and into the session for the shopping cart. Well, I need to also send a price id variable so that the cart will know which price to use. This is because they want to offer pricing on a per-day basis. How would I modify the cart.php page to accomplish this? I have tried, but cannot get the entire thing to work. All help is appreciated. Below is my code: Code: [Select] <?php // if no session is set, initiate one if (!isset($_SESSION)) { session_start(); } // see if the customer is logged in //if (!isset($_SESSION['customer_id'])) //{ //header("location:login.php"); //} // connect to the database require_once('connect.php'); // select the database mysql_select_db($database, $connect); // get the video information if (isset($_GET['video_id'])) { $video_id = $_GET['video_id']; } else { $video_id = 1; } // get the action if (isset($_GET['action'])) { $action = $_GET['action']; } else { $action = "empty"; } // get the video pricing information if (isset($_GET['price_id'])) { $price_id = $_GET['price_id']; } else { $price_id = ""; } // do the following code based on the action switch($action) { // if the action is add then add the product id to the cart session array case "add": if (isset($_SESSION['cart'][$video_id])) { $_SESSION['cart'][$video_id]++; } else { $_SESSION['cart'][$video_id] = 1; } break; // if the action is remove then remove the product id from the cart session array case "remove": if (isset($_SESSION['cart'][$video_id])) { $_SESSION['cart'][$video_id]--; if ($_SESSION['cart'][$video_id]==0) { unset($_SESSION['cart']); } } break; // if the action is empty then remove the cart session array completely case "empty": unset($_SESSION['cart']); break; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="Description" content="Information architecture, Web Design, Web Standards." /> <meta name="Keywords" content="your, keywords" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="layout.css" type="text/css" /> <title>Straight Muscle Videos...Pay-Per-View Alpha Male Muscle Worship Videos</title> </head> <body> <!--wrap starts here--> <div id="wrap"> <?php include('header.php'); ?> <?php include('menu.php'); ?> <!--content-wrap starts here--> <div id="content-wrap" class="two-col"> <?php include('sidebar.php'); ?> <!--main content starts here--> <div id="main"> <h1>Shopping Cart</h1> <br /> <?php if (isset($_SESSION['cart'])) { $total = 0; ?> <table width="95%" border="0" cellspacing="0" cellpadding="5"> <?php foreach($_SESSION['cart'] as $video_id => $x) { $query = mysql_query("SELECT VideoId, VideoTitle, PriceId, PriceVideoId, PriceAmount, PriceTimeId, TimeId, TimeTitle, TimeLength FROM Video, Price, Time WHERE VideoId = $video_id AND PriceId = $price_id AND PriceVideoId = $video_id AND PriceTimeId = TimeId", $connect); $row = mysql_fetch_array($query); $video_name = $row['VideoTitle']; $order_length = $row['TimeTitle']; $video_price = $row['PriceAmount']; $line_cost = $video_price * $x; $total_cost = $total + $line_cost; ?> <tr> <td align="left" valign="middle"><?php echo $video_name; ?></td> <td align="center" valign="middle"><?php echo $order_length; ?></td> <td align="center" valign="middle"><?php echo "$".$line_cost; ?></td> <td align="center" valign="middle"><a href="cart.php?action=remove&video_id=<?php echo $video_id; ?>&price_id=<?php echo $price_id; ?>">Remove</a></td> </tr> <?php } ?> <tr> <td colspan="4" bgcolor="#666666"><span class="shopping_cart">Purchase Total: $<?php echo $total_cost; ?></span></td> </tr> </table> <div align="center"> <form id="shopping_cart" method="post" action="confirm.php"> <input type="submit" name="place_order" id="place_order" value="Place Order" /> </form> </div> <div align="center"> <p><a href="search.php">Continue Shopping</a></p> <p><a href="cart.php?action=empty">Empty Cart</a></p> </div> <?php } else { echo "<br /><br /><div align='center'>There are no items in your cart.</div>"; } ?> <!--main content ends here--> </div> <!--content-wrap ends here--> </div> <?php include('footer.php'); ?> <!--wrap ends here--> </div> </body> </html> Hello. I want to implement a simple shopping cart with sessions but without using DB, despite the fact that I have a DB consisting of Car-Shop-Customer. Is the only way using arrays? Need some help on developing the steps below I am working on a website money collection system that consist of stores affiliating to the website and sales their products in the website as independent stores. But I am not sure how to collect the percentage I will deduct per transaction for the stores. I have elaborated two plans but I don't know is those a good ideas in terms of bringing more store in to the website and have them comfortable by the way the website hold business with their stores owners. 1- I was thinking of collecting all the money of transactions into a single paypal account and then try to pay them weekly or in a monthly basis. (I am not sure about this first option because I don't know whether the store owners will be thinking to much into it at the time of making a decision to register and to sell their products in the website. I guess they might think whether the website administrator will delivery the money every week, or if the website administrators are going to steal them etc. So this option I don't know if with some changes can be implemented. 2- The second option was to let each store administer each transaction with their credit/debit machine they have at the store and make the transaction right there and then on a monthly or weekly basis the website administrator charge them for the amount of transaction done during that time period in the website. 3- Third option is create a paypal account for each store and at the moment of the transaction to transfer the money to each store account and have the website paypal account deduct its percentage from the transaction and have the store owner paypal account deduct its part. For healthy business purpose and website grow in terms of acquiring more stores into the website which of those three options would be the best option to choose or if there is another idea even better for business grow and comfortability among stores owner that you guys might have in mind share it. Is selecting an option relevant to the grow of the website or it is? co.ador HI,
Im trying to adapt a shopping cart script for an alternative use, on my local host XXMP scrip code works fine, but when i upload to my host I have problems,
Im making a Role-play page to assist with npc encounters, where you can add npc's to the encounter (Shopping Cart) see http://rptoolkit.com/encounter/ which is active and working
The issue is when I go to remove 1 of the 4 people from the encounter (Cart) it will remove all and duplicate the first entry on 2 lines, where this doesn't happen on my localhost.
Hope you can help shed some light as I'm confused why it will work on 1 but not the other maybe has to do with my PHP Versions.
Thanks.
----------------------------------------------------
Script code is below for the remove link button on the index page
echo '<td><span> <a href="include/encounter_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'"><img src="images/icon_delete.gif" alt="Delete"></a> </span></td>'; Hello all, so I'm in sort of a pickle here. I've been using a php tutorial on Youtube and I got to a point where i have to add products to cart using a users IP address. So far I've got no error pop up or anything. The scripts I've typed out in my functions.php are working well no error. But when I get to adding products using the website, the page only blinks , no items are added to the cart database and even the script alert which I'd set to echo doesn't display. Can you find a way to help me out of this? Below is my code...
function getRealIpUser(){ switch(true){ case(!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP']; case(!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP']; case(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR']; default : return $_SERVER['REMOTE_ADDR']; } } function add_cart(){ global $db; if (isset($_GET['add_cart'])) { $ip_add =getRealIpUser(); $p_id = $_GET['add_cart']; $product_qty = $_POST['product_qty']; $product_size = $_POST['product_size']; $check_product = "SELECT * FROM cart WHERE ip_add='$ip_add' AND p_id='$p_id'"; $run_check = mysqli_query($db,$check_product); if (mysqli_num_rows($run_check)>0) { echo "<script>alert('This product has already added in cart')</script>"; echo "<script>window.open('details.php?pro_id=$p_id','_self')</script>"; } else { $query = "INSERT INTO cart (p_id,ip_add,qty,size) VALUES ('$p_id','$ip_add','$product_qty','$product_size')"; $run_query = mysqli_query($db,$query); echo "<script>window.open('details.php?pro_id=$p_id','_self')</script>"; } } }
I am using php 7 , Apache, MySQL.... Any help will be much appreciated.
I have a form which gets filled in with values from a session array. This form also has just one update button. If I have 3 items in my cart and I want to update just one of the items how would I pass the id of that product to my cart class? The problem I'm having is the id of the last product in the cart is passed so the update never works unless its the last item thats being updated. If I was to wrap each item in a form with an add update button it will work the way I want it to work but I really dont want to add extra buttons. Is there anyway to to wrap all the items in one form and get just the input values of the item whos quantity is being changed. Here is the cart form: Code: [Select] <form action="index.php?view=update_cart" method="post" > <table id="items"> <thead> <tr> <th>Item</th> <th>Item Price</th> <th>Qty</th> <th>Subtotal</th> <!-- <th>Edit</th>--> </tr> </thead> <tbody> <?php foreach($cart->Cart() as $item):?> <!--<form action="index.php?view=update_cart" method="post" >--> <input type="hidden" id="prodId" name="prodId" value="<?php echo $item['Id']; ?>" /> <tr> <td><?php echo $item['Product']; ?></td> <td><?php echo '$'.$item['Price']; ?></td> <td><input type="text" size="2" name="qty" maxlength="2" value="<?php echo $item['Quantity']; ?>" onsubmit="this.value"/></td> <td><?php echo '$'.number_format($item['Price']*$item['Quantity'],2); ?></td> <!--td><input type="submit" name="update" value="Update" /></td--> </tr> <!--</form>--> <?php endforeach; ?> </tbody> </table> <p><input type="submit" name="update" value="Update" /></p> </form> When I debug my code and hover over the $_POST['prodId'] i will see the id of the last product. Any help will be appricated thanks. Can someone give me name of free shopping cart with auctions(offers) like Open Classifieds ? hello all, hoping someone can help, i am still pretty new to php and i am stuck on creating a php cart. the code i have below is working, but the problem i am having is i need a store in the session array i am struggling to get my head around it so hoping someone can help here. i am hoping to have $product_id (which is currently in) $option1,2,3 and $text (for a textarea box) heres my function file function get_product() { echo "Hello"; } function add_product() { $product_id = $_POST['product_id']; if ($product_id == 'NULL') { echo "No Product Selected!"; } if (isset($_SESSION['cart'][$product_id])) { $_SESSION['cart'][$product_id]++; echo "<script>window.location='product.php'</script>"; }else{ $_SESSION['cart'][$product_id] = 1; echo "<script>window.location='product.php'</script>"; } } function increase_product() { $product_id = $_GET['product_id']; $_SESSION['cart'][$product_id]++; echo "<script>window.location='cart.php'</script>"; } function decrease_product() { $product_id = $_GET['product_id']; $_SESSION['cart'][$product_id]--; echo "<script>window.location='cart.php'</script>"; } function empty_cart() { unset($_SESSION['cart']); echo "<script>window.location='cart.php'</script>"; } }() my product page (currently with out the extra form items (option1,2,3 etc) include '_class/cart.php';$core->session($mode = 'start');if(isset($_POST['buy'])){$cart->add_product();}?><!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>Product</title></head><body><?php $core->navbar();?><form method="post" action=""><input name="product_id" type="hidden" value="Coffee" /><h1>Cup Of Coffee</h1><p>Buy me you know you want too!</p><input name="buy" type="submit" value="Add To Basket" id="buy" /></form><form method="post" action=""><input name="product_id" type="hidden" value="Biscuits" /><h1>Barrel Of Biscuits</h1><p>When Coffee Just Gives You The Munchies!</p><input name="buy" type="submit" value="Add To Basket" id="buy" /></form></body></html>() my include cart file if (isset($_SESSION['cart'])) {//Session Cart foreach($_SESSION['cart'] as $product_id => $quantity){//Session Array if($quantity < 1){//Quantity Less Then 1 unset($_SESSION['cart'][$product_id]); echo "<script>window.location='cart.php'</script>"; }//End Quantity Less Then 1 if(!$_SESSION['cart']){//Cart Array Empty unset($_SESSION['cart']); echo "<script>window.location='cart.php'</script>"; }//End Cart Array Empty if ($product_id != NULL){//Show Products echo '<h1>' . $product_id . '</h1>'; echo "Quantity <br>"; ?><a href="cart.php?product_id=<?php echo $product_id; ?>&option=increase">+</a> <?php echo $quantity; ?> <a href="cart.php?product_id=<?php echo $product_id; ?>&option=decrease">-</a><?php }//End Show Products }//End Session Array require 'library/paypal.php'; }else{ echo "Your Basket Is Empty"; }//End Session Cart() and my actual cart file include '_class/cart.php';$core->session($mode = 'start');?><!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>Cart</title></head><body><?php$core->navbar(); if (isset($_GET['product_id']['option'])) { $product_id = $_GET['product_id']; $option = $_GET['option']; if ($option == 'decrease'){ $cart->decrease_product(); } if ($option == 'increase'){ $cart->increase_product(); } }elseif (isset($_GET['option'])){ $option = $_GET['option']; if ($option == 'empty'){ $cart->empty_cart(); } }else{ require 'library/cart.php'; }?><p><a href="cart.php?option=empty">Empty Cart</a></p></body></html>() please explain answers or exmples as clear as possible thanks everyone everything seems to b working correctly...except 'update cart' where if i click on update cart button it redirects me to d previous page...instead of calculating the input.. i m not able 2 figure out what d problem is.. here's d cart.php: <?php require_once 'library/config.php'; require_once 'library/cart-functions.php'; $action = (isset($_GET['action']) && $_GET['action'] != '') ? $_GET['action'] : 'view'; switch ($action) { case 'add' : addToCart(); break; case 'update' : updateCart(); break; case 'delete' : deleteFromCart(); break; case 'view' : } $cartContent = getCartContent(); $numItem = count($cartContent); $pageTitle = 'Shopping Cart'; require_once 'include/header.php'; // show the error message ( if we have any ) displayError(); if ($numItem > 0 ) { ?> <form action="<?php echo $_SERVER['PHP_SELF'] .'?action=update'; ?>" method="POST" name="frmCart" id="frmCart"> <table width="780" border="0" align="center" cellpadding="5" cellspacing="1" class="entryTable"> <tr class="entryTableHeader"> <td colspan="2" align="center">Item</td> <td align="center">Unit Price</td> <td width="75" align="center">Quantity</td> <td align="center">Total</td> <td width="75" align="center"> </td> </tr> <?php $subTotal = 0; for ($i = 0; $i < $numItem; $i++) { extract($cartContent[$i]); $productUrl = "index.php?c=$cat_id&p=$pd_id"; $subTotal += $pd_price * $ct_qty; ?> <tr class="content"> <td width="80" align="center"><a href="<?php echo $productUrl; ?>"><img src="<?php echo $pd_thumbnail; ?>" border="0"></a></td> <td><a href="<?php echo $productUrl; ?>"><?php echo $pd_name; ?></a></td> <td align="right"><?php echo displayAmount($pd_price); ?></td> <td width="75"><input name="txtQty[]" type="text" id="txtQty[]" size="5" value="<?php echo $ct_qty; ?>" class="box" onKeyUp="checkNumber(this);"> <input name="hidCartId[]" type="hidden" value="<?php echo $ct_id; ?>"> <input name="hidProductId[]" type="hidden" value="<?php echo $pd_id; ?>"> </td> <td align="right"><?php echo displayAmount($pd_price * $ct_qty); ?></td> <td width="75" align="center"> <input name="btnDelete" type="button" id="btnDelete" value="Delete" onClick="window.location.href='<?php echo $_SERVER['PHP_SELF'] . "?action=delete&cid=$ct_id"; ?>';" class="box"> </td> </tr> <?php } ?> <tr class="content"> <td colspan="4" align="right">Sub-total</td> <td align="right"><?php echo displayAmount($subTotal); ?></td> <td width="75" align="center"> </td> </tr> <tr class="content"> <td colspan="4" align="right">Shipping </td> <td align="right"><?php echo displayAmount($shopConfig['shippingCost']); ?></td> <td width="75" align="center"> </td> </tr> <tr class="content"> <td colspan="4" align="right">Total </td> <td align="right"><?php echo displayAmount($subTotal + $shopConfig['shippingCost']); ?></td> <td width="75" align="center"> </td> </tr> <tr class="content"> <td colspan="5" align="right"> </td> <td width="75" align="center"> <input name="btnUpdate" type="submit" id="btnUpdate" value="Update Cart" class="box"></td> </tr> </table> </form> <?php } else { ?> <p> </p><table width="550" border="0" align="center" cellpadding="10" cellspacing="0"> <tr> <td><p align="center">You shopping cart is empty</p> <p>If you find you are unable to add anything to your cart, please ensure that your internet browser has cookies enabled and that any other security software is not blocking your shopping session.</p></td> </tr> </table> <?php } $shoppingReturnUrl = isset($_SESSION['shop_return_url']) ? $_SESSION['shop_return_url'] : 'index.php'; ?> <table width="550" border="0" align="center" cellpadding="10" cellspacing="0"> <tr align="center"> <td><input name="btnContinue" type="button" id="btnContinue" value="<< Continue Shopping" onClick="window.location.href='<?php echo $shoppingReturnUrl; ?>';" class="box"></td> <?php if ($numItem > 0) { ?> <td><input name="btnCheckout" type="button" id="btnCheckout" value="Proceed To Checkout >>" onClick="window.location.href='checkout.php?step=1';" class="box"></td> <?php } ?> </tr> </table> <?php require_once 'include/footer.php'; ?> and here is update cart function: function updateCart() { $cartId = $_POST['hidCartId']; $productId = $_POST['hidProductId']; $itemQty = $_POST['txtQty']; $numItem = count($itemQty); $numDeleted = 0; $notice = ''; for ($i = 0; $i < $numItem; $i++) { $newQty = (int)$itemQty[$i]; if ($newQty < 1) { // remove this item from shopping cart deleteFromCart($cartId[$i]); $numDeleted += 1; } else { // check current stock $sql = "SELECT pd_name, pd_qty FROM tbl_product WHERE pd_id = {$productId[$i]}"; $result = dbQuery($sql); $row = dbFetchAssoc($result); if ($newQty > $row['pd_qty']) { // we only have this much in stock $newQty = $row['pd_qty']; // if the customer put more than // we have in stock, give a notice if ($row['pd_qty'] > 0) { setError('The quantity you have requested is more than we currently have in stock. The number available is indicated in the "Quantity" box. '); } else { // the product is no longer in stock setError('Sorry, but the product you want (' . $row['pd_name'] . ') is no longer in stock'); // remove this item from shopping cart deleteFromCart($cartId[$i]); $numDeleted += 1; } } // update product quantity $sql = "UPDATE tbl_cart SET ct_qty = $newQty WHERE ct_id = {$cartId[$i]}"; dbQuery($sql); } } if ($numDeleted == $numItem) { // if all item deleted return to the last page that // the customer visited before going to shopping cart header("Location: $returnUrl" . $_SESSION['shop_return_url']); } else { header('Location: cart.php'); } exit; } Hello, I'm trying to implement a function called 'delete_cart' but I can't seem to get it working. Here's the function code: Code: [Select] function delete_cart(){ unset($_SESSION['cart']); } Here's the HTML / php code: Code: [Select] if (!empty($_SESSION['cart'])) { echo '<a href="index.php?p=cart?delete_cart=true">delete cart</a> '; } When you click on 'delete cart', the page just refreshes to the home page and I am able to re-visit that same cart with the same items in. I've also noticed when I log out, the shopping cart is deleted. Hey all not been on here for a few years, been out of work. i am back and throwing ,myself straight into the deep end. Is it hard to integrate a shopping cart into a website. Any good example snippets of code to look at? I have a little search but someone always seems to know a better one. Why are almost all tutorials these days you have to pay for (times are getting hard ). Hi All I have my shopping cart working correctly, just a small tweak which i would like to make to it. Here is the code i currently use... Code: [Select] echo '<p>' . $fldname . ' <a href="cart.php?action=add&id=' . $row['idinfo'] . '">Add to report</a></p>'; But i want it so that when i click 'Add to report' is does not take me to cart.php, but it still adds the item into the shopping cart. kind of just refeshs the current page? Im sure it is only a small tweak which needs to be done.. Any help would be great -Dream I have followed a shopping cart tutorial from this website. http://v3.thewatchmakerproject.com/journal/276/ 1. When you refresh the page it adds another item to the cart. 2. I would like to add an image of the products from a folder and the link of the images in the database. Can some one please help. Urgently! Thanks. |