PHP - Shopping Cart Quantity Refresh Defaults To One
Hi Guys
I have a shopping cart where the quantity refresh keeps defaulting to one (i.e. you change it from one to ten and the page refreshes and defaults back to one). This is the automatic refresh, not clicking a button. We have lots of other carts using almost the exact same code and they work fine. I can swap over the code in the html page for something more basic and it works. I have compared the basket.php files (both in the lib folder and the html folder - we are using smarty templates) with working sites and they are identical. Here is the basket.html code: Code: [Select] <form action="basket.html" method="post" name="update" id="update" > <table class="basket-table" cellpadding="0" cellspacing="0"> <tr> <th width="64">Item</th> <th width="285" class="basket-desc">Item Description</th> <th width="47">Quantity</th> <th width="82">Price</th> <th width="53" class="no-rb">Remove</th> </tr> <!--{section name=c loop=$basket.products}--> <tr class="<!--{cycle values="colour1,colour2"}--><!--{if $smarty.section.c.last}--> no-bb<!--{/if}-->"> <td><!--{if isset($basket.products[c].image) }--><a href="/category/<!--{$basket.products[c].categoryLink}-->/product/<!--{$basket.products[c].link}-->/<!--{if $basket.products[c].hasSiblings}-->?option=<!--{$basket.products[c].productOptionId}--><!--{/if}-->"><img src="<!--{$basket.products[c].image}-->" alt="<!--{$basket.products[c].title}-->" class="img-border" /></a><!--{else}--> <!--{/if}--></td> <td class="basket-desc"><a href="/category/<!--{$basket.products[c].categoryLink}-->/product/<!--{$basket.products[c].link}-->/<!--{if $basket.products[c].hasSiblings}-->?option=<!--{$basket.products[c].productOptionId}--><!--{/if}-->"><!--{$basket.products[c].prodtitle}--> <!--{if $basket.products[c].hasSiblings}--><!--{$basket.products[c].optiontitle}-->:<!--{$basket.products[c].title}--><!--{/if}--></a></td> <td><input name="quantity<!--{$smarty.section.c.index}-->" id="<!--{$basket.products[c].prodtitle}-->" value="<!--{$basket.products[c].quantity}-->" maxlength="3" onchange="this.form.submit()" type="text" /></td> <td>£<!--{$basket.products[c].lineTotal|string_format:"%.2f"}--></td> <td class="no-rb"><a href="/basket.html?action=delete&po=<!--{$basket.products[c].productOptionId}-->"><img src="/images/btn_bin.gif" alt="Remove" title="Remove" /></a></td> </tr> <!--{/section}--> </table> <div class="basket-text"> Free UK mainland delivery on order value over £150 </div> <div class="basket-shipping"> <label for="region">Choose Shipping Region</label> <select name="region" id="region" onchange="this.form.submit();"> <!--{html_options options=$region selected=$basket.region}--> </select> </div> <div class="basket-prices"> <span>Sub-Total:</span><span class="subtotal">£<!--{$basket.totalPrice|string_format:"%.2f"}--></span> <span>Delivery:</span><span class="subtotal">£<!--{if isset($basket.shipping.dprice)}--><!--{$basket.shipping.dprice}--><!--{else}-->0.00<!--{/if}--></span> <span>VAT:</span><span class="subtotal">£<!--{$basket.totalTaxIncShipping|string_format:"%.2f"}--></span> </div> <div class="clear"></div> <div class="coupon"> <img src="images/logo_coupon.gif" alt="Radmore & Tucker" align="left" /> <label for="coupon">Enter Coupon Code</label> <input name="coupon" id="coupon" onchange="this.form.submit()" type="text" /> </div> <div class="updatetext"> After making any changes to the quantity or shipping please use the update button to amend your total<br /> <input type="image" src="/images/btn_update.gif" alt="update" value="submit" /> </div> <div class="clear"></div> <!--{if isset($basket.totalDiscountTaxed) && $basket.totalDiscountTaxed neq '0'}--> <div class="total"> Discount: <span>£<!--{$basket.totalDiscountTaxed|string_format:"%.2f"}--></span> </div> <div class="clear"></div> <!--{/if}--> <div class="total"> Total: <span>£<!--{$basket.totalPriceIncShippingTaxed|string_format:"%.2f"}--></span> </div> <div class="clear"></div> <input type="hidden" name="formAction" value="update"/> <a href="/checkout.html" class="btn-continue"><img src="/images/btn_continue.gif" alt="continue" title="Continue To Checkout" /></a> </form> The other refreshes work (region and coupon). I think the problem is in the line: Code: [Select] <input name="quantity<!--{$smarty.section.c.index}-->" id="<!--{$basket.products[c].prodtitle}-->" value="<!--{$basket.products[c].quantity}-->" maxlength="3" onchange="this.form.submit()" type="text" /> this is the basket.php from the html folder: Code: [Select] <?php require_once('../lib/config.php'); require_once(LIBDIR . "app_top.php"); require_once(LIBDIR . "region.php"); $params = processParams(); // get the regions $region = new region_collection(); $clist = $region->getRegionList(); $smarty->assign("region", $clist); if (isset($_POST['formAction']) && $_POST['formAction'] == "update") { updateBasket(); } elseif (isset($_GET['action']) && $_GET['action'] == "delete") { if (isset($_GET['po']) && is_numeric($_GET['po'])) { $basket->edit($_GET['po'], 0); } } if (isset($_POST['region']) && is_numeric($_POST['region'])){ $_SESSION['region'] = intval($_POST['region']); } //print_r($basket->output()); if (isset($_SESSION['discountCode'])) { $message = $basket->coupon($_SESSION['discountCode']); $smarty->assign('message',$message); } //print_r($basket->output()); $smarty->assign('basket', htmlescape($basket->output())); if(isset($_GET['perror']) && $_GET['perror'] == "1"){ $smarty->assign('message',"There has been a error with the SagePay payment gateway. <br/><br/> Your order has been saved on the system email or phone Radmore and Tucker to proceed with the order."); }elseif(isset($_GET['perror']) && $_GET['perror'] == "2"){ $smarty->assign('message',"Item/Items in your basket no long have the required quantity, your basket has been updated, plaese check before proceeding with the order."); } display('basket.html'); function updateBasket() { global $smarty, $params, $basket; for ($i=0;$i<count($_POST);$i++) { if (isset($_POST['productOption' . $i]) && is_numeric($_POST['productOption' .$i]) && isset($_POST['quantity' . $i]) && is_numeric($_POST['quantity' . $i])) { $backVale = $basket->edit($_POST['productOption' . $i], $_POST['quantity' . $i]); if ($backVale !== true){ $errorsUpdate[] = $backVale; } } } if (isset($_POST['coupon']) && !empty($_POST['coupon'])) { $message = $basket->coupon($_POST['coupon']); $smarty->assign('message',$message); } if(isset($errorsUpdate) && !empty($errorsUpdate)){ $smarty->assign('errorUpdate',implode("<br />", $errorsUpdate)); } return; } function display($screen) { global $smarty, $params; $smarty->assign('backlink', $params['backlink']); $smarty->display($screen); exit(); } function processParams() { $params = array(); if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], SITEURL) === 0 && strpos($_SERVER['HTTP_REFERER'], "basket") === false && strpos($_SERVER['HTTP_REFERER'], "checkout") === false) { $params['backlink'] = "/" . str_replace(SITEURL, "" ,$_SERVER['HTTP_REFERER']); } elseif (isset($_SESSION['backlink'])) { $params['backlink'] = $_SESSION['backlink']; } else { $params['backlink'] = "/index.html"; } $params['backlink'] = preg_replace("/\?.*/", "", $params['backlink']); $_SESSION['backlink'] = $params['backlink']; return $params; } ?> Here is a snippet from the basket.php file in the lib folder.I hope I have grabbed the relevant bit (have attached the full file just in case). Code: [Select] /** * adds product to the basket * @params int $option the product option id * @params int $quantity the quantity of the products to add */ function add($product, $option, $quantity) { if (!isset($option) || !is_numeric($option)) { //trigger_error("No options selected"); return false; } if (!isset($quantity) || !is_numeric($quantity) || $quantity < 1 ) { trigger_error("No quantity selected"); return false; } if (!isset($product) || !is_numeric($product) || $product < 1) { trigger_error("No product selected"); return false; } /** * if the session var doesn't already exist recreate it */ if (!isset($_SESSION['basket']) || !is_array($_SESSION['basket'])) { $_SESSION['basket'] = array(); $_SESSION['basketinfo'] = array(); } sort($_SESSION['basket']); Any help the community can give would this would be much appreciated. Similar TutorialsI have setup a website that has a shopping basket and it displays the objects ordered in a table before being purchased, i have added a plus and minus button to adjust the quantity using the following code:
$add ="<form action='cart.php' method='post'><input type='hidden' name='additem' value='$id'/><input type='submit' name='itemadd' onclick='CheckQty()' value='+'/></form>"; $sub ="<form name='sub' action='cart.php' method='post'><input type='hidden' name='subitem' value='$id'/><input type='submit' name='itemsub' value='-'/></form>"; //add to quantity of item if (isset($_POST['itemadd'])){ $additem = $_POST['additem']; if ($qty < 5){ $addqty = $qty + 1; $adding = "UPDATE orders SET quantity = '$addqty' WHERE id = '$additem'"; $add_query = mysqli_query($db_conx, $adding); header('Location: http://www.quichlicious.co.uk/cart.php'); //print $additem; exit(); } else { $usemes = "You have reached maximum quantity"; } } //subtract to quantity of item if (isset($_POST['itemsub']) && ($_POST['itemsub'] !="")){ $subitem = $_POST['subitem']; if ($qty > 1){ $subqty = $qty - 1; $subing = "UPDATE orders SET quantity = '$subqty' WHERE id = '$subitem'"; $sub_query = mysqli_query($db_conx, $subing); header("location: cart.php"); exit(); } else { $usemes = "<font color='red'>Please use delete to remove item</font>"; } }The issue i have is it works great if just one item is in the basket but if i have more than 1 item in the basket i can only adjust the very last item in the baskets quantity and the others just randomly jump numbers or will not change at all? $additem gets the item ID from the table. Edited by mik_se7, 19 November 2014 - 10:14 AM. 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>
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> 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 ). 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 } ?> 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 i make a shopping cart,but it dont show the product i have choose. it suppose to show the product i choose at the cart table but its still show the "Your Cart is empty" result..im still new.i follow the instruction from the youtube.sorry for my bad english.
here is the index2.php code
<? session_start(); require("connection.php"); if(isset($_GET['page'])){ $pages=array("products", "cart"); if(in_array($_GET['page'], $pages)) { $_page=$_GET['page']; }else{ $_page="products"; } }else{ $_page="products"; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> <body> </body> </html> <link rel="stylesheet" href="style2.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { }); </script> </head> <body> <div id="container"> <div id="main"> <?php require($_page.".php"); ?> </div> <div id="sidebar"> <h1>Cart</h1> <?php if(isset($_SESSION['cart'])){ $sql="SELECT * FROM products WHERE id_product IN ("; foreach($_SESSION['cart'] as $id => $value) { $sql.=$id.","; } $sql=substr($sql, 0, -1).") ORDER BY name ASC"; $query=mysql_query($sql); while($row=mysql_fetch_array($query)){ ?> <p><?php echo $row['name'] ?> x <?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?></p> <?php } }else{ echo "<p>Your Cart is empty</p>"; } ?> </div> </div> </body>and this is the products.php code <?php if(isset($_GET['action']) && $_GET['action']=="add"){ $id=intval($_GET['id']); if(isset($_SESSION['cart'][$id])){ $_SESSION['cart'][$id]['quantity']++; }else{ $sql_s="SELECT * FROM products WHERE id_product={$id}"; $query_s=mysql_query($sql_s); if(mysql_num_rows($query_s)!=0){ $row_s=mysql_fetch_array($query_s); $_SESSION['cart'][$row_s['id_product']]=array( "quantity" => 1, "price" => $row_s['price'] ); }else{ $message="This product id it's invalid!"; } } } ?> <h1>Product List</h1> <?php if(isset($message)){ echo "<h2>$message</h2>"; } ?> <table> <tr> <th>Name</th> <th>Description</th> <th>Price</th> <th>Action</th> </tr> <?php $sql="SELECT * FROM products ORDER BY name ASC"; $query=mysql_query($sql); while ($row=mysql_fetch_array($query)) { ?> <tr> <td><?php echo $row['name'] ?></td> <td><?php echo $row['description'] ?></td> <td><?php echo $row['price'] ?></td> <td><a href="index2.php?page=products&action=add$id=<?php echo $row['id_product'] ?>">Add To Cart</a></td> </tr> <?php } ?> </table> Can someone give me name of free shopping cart with auctions(offers) like Open Classifieds ? 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. 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. 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 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 ? Hello. I could use some advice on the best way to handle my shopping cart. My website will sell subscriptions along with more traditional items like books, t-shirts, etc. For subscriptions, I have these business rules... 1.) Only non-members can purchase a "trial subscription". 2.) Once you are a "member", then no more trials for you! 3.) You can purchase multiple subscriptions (e.g. into the future), BUT I only allow you to purchase ONE subscription at a time. (My system would allow multiple purchases at once, but I don't ant people accidentally signing up for 2 years and then i have to clean things up. Also, I want the transition from a "trial" to a "full paid" subscription to be clear.) 4.) if I ever offer multiple "trial" offers, then you only get to take advantage of one, and then after that it's on to full paid subscriptions for you - although I will run "promos".
Here is the problem... Nothing stops a non-member (or a member) from adding a "paid" and a "trial" subscription into their shopping cart. Or multiple "trial" subscriptions. Or multiple "paid" subscriptions. (Maybe someone adds a paid subscription on Friday, then the weekend comes, and on Monday they notice the trial subscription offer and add that forgetting about the paid subscription.) Or maybe someone is trying to "game" things, and adds 3 "trial" subscriptions and tries to check out?!
How should my website (gracefully) handle these scenarios?
1.) Am I aggressive up front, and prevent people from adding a 2nd subscription to their shopping cart as they shop? 2.) Or do I allow them to go wild while shopping, but then address the issue at checkout? 3.) Should my code be doing the work, or is the onus on the user to go in and clean up their shopping cart? 4.) If I address this issue at checkout, then do I need to add extra functionality to adjust their shopping cart from the checkout page on-the-fly? Or do I send them back to their actual shopping cart page and make them clean things up there? 5.) What do I do if someone has already added other items to their cart previously (e.g. T-shirts). Do I handle the "Get this offer" separately hoping to get them signed up ASAP, and then leave the T-shirts in their cart to purchase later? Or do I handle everything at once? (If they just have a "trial" subscription and a T-shirt, no worries. But if they have a "paid" subscription and then add a "trial" subscription and are looking for a quick checkout, then the scenarios/concerns above come into play...)
The stuff I was asking about last night is what got me to thinking about all of this. The flow was supposed to go... User sees "get one month for $1" on the home page, clicks the button, gets a trail-offer details paid, clicks "Get this offer", and wah-lah, they are on the checkout page! But if they already have things in their cart or maybe click the offer button 10 times, then things get messier. My concern is that converting a user to a paid member is the #1 goal, and I don't want other things to get in the way, whether that is a complicated checkout or things getting distracted purchasing other things like T-shirts! At the same time, if you want to buy multiple things, all the better as long as you follow my business rules.
So what's the best way to not be a pain to shoppers, but to maintain the rules I mention above? Edited September 9, 2020 by requinix edited at author's request For a project I have to create a simple form that allows a user to order a pair of trainers. I understand how to do as the project outlines, but would like to expand on it. Would it be possible for me to substitute a MySQL database for an array that contains an array of products. So that when the user makes an order, the quantity in the array is reduced. The array would look as follows: $prod = array( array( 'id' => '00001', 'name' => 'Pink Converse', 'desc' => 'This is the description of the product.', 'price' => 4500, 'quantity' => 2, 'img' => 'images/prod1.jpg', 'img2' => 'images/00001-2.jpg' ), array( 'id' => '00002', 'name' => 'Tartan Nike Hi-Tops', 'desc' => 'This is the description of the product.', 'price' => 5500, 'quantity' => 2, 'img' => 'images/prod2.jpg', 'img2' => 'images/00002-2.jpg' ), array( 'id' => '00003', 'name' => 'Black Hi-Tops', 'desc' => 'This is the description of the product.', 'price' => 5500, 'quantity' => 2, 'img' => 'images/prod3.jpg', 'img2' => 'images/00003-2.jpg' ), array( 'id' => '00004', 'name' => 'Smart Mens Shoes', 'desc' => 'This is the description of the product.', 'price' => 7000, 'quantity' => 2, 'img' => 'images/prod3.jpg', 'img2' => 'images/00004-2.jpg' ) ); If you know if this is possible or not, you would be a great help, any ideas would also be welcome. Thanks Hello. I'm trying to figure out the most logical way to update my shopping cart (table). When my checkout.php script loads, I need to run some checks on all cart items and take appropriate action. For example, a "Trial Offer" is only available to non-Members, so if a Member somehow has a "Trial Offer" in his/her shopping cart then I'd like my checkout.php script to remove that automatically from the Member's cart. So when checkout.php loads, one of the first things I do is to read the user's shopping cart items from the database. But what is the most logical way to update the shopping cart table? Do I load the shopping cart records into an array, then iterate through them, remove any non-applicable "Trial Offers" and then write things back to the shopping cart table? (If so, then how do I merge things? This is what is confusing me...) Or do I somehow iterate through the shopping cart records for the user and update each record at a time and avoid loading things into memory like using an array? Again, this seems like a simple enough task, but I'm not sure the smartest way to do things?!
Need help with this code, if someone can help me.. // current session id $sid = session_id(); // check if the product is already // in cart table for this session $sql = "SELECT pd_id FROM tbl_cart WHERE pd_id = $productId AND ct_session_id = '$sid'"; $result = dbQuery($sql); There is a problem with $sid = session_id();, in my code, that function always get me 0 in my php code.. do i need to set this in some other way.. Anyway, there are no registred users, i just need to set session for current user.. Like this tutorial: Code: [Select] http://www.phpwebcommerce.com/shop-add-to-cart.php Hi guys I'm making a shopping cart where the admin can login and post an item for sale like the example below when posting an new item they will post the details as above. I need a way so when they click the button buy it will link them to paypal with the price specified and then when purchase is successful I can display the details to the buyer. any idea on how I would go around doing this. thanks Hi guy's, I'm trying to integrate a shopping cart, but my knowledge is lacking. I've tried allot, but mostly it resulted in displaying nothing or a bunch of errors. Here's where i'm at. Code: [Select] function getProducts() { //Function to display the products on the front end //Create the MYSQL db connection $db = new Connection(DB_HOST, DB_USER, DB_PASS, T4_DB_NAME); //Query the DB for all the products $result = $db->query('SELECT * FROM user_photos'); // for testing purposes //Set the items variable so that you can add to it in the loop below $items = ''; //Loop through the mysql results $id = $_GET['id']; $username = $_GET['username']; // NOTE: if i do a while here, it display's all pictures of every user and loops the pictures for 16 times. // If i do a if i can click the image, but the thumnail is not displaying and the title is that of the admin // and only one image is displayed, while a user has more pictures. while($row = mysql_fetch_assoc($result)) { $items .= ' <div class="product"> <h3>'.stripslashes($row['title']).'</h3> <div class="info"> <a href=/secure/users/'.$username .'/pics/'. stripslashes($row['reference']).'> <img src=/secure/users/'.$username .'/pics/thumbs/'. stripslashes($row['thumbnail']).'></a> <div class="price">€'.number_format($row['price'], 2).'</div> <a href="addToCart.php?ID='.$id.'">Add to cart</a> </div> </div> '; } echo $items; } See NOTE in code: // NOTE: if i do a while here, it display's all pictures of every user and loops the pictures for 16 times. // If i do a if i can click the image, but the thumnail is not displaying and the title is that of the admin // and only one image is displayed, while a user has more pictures. (id=1) while it should be 25. (title= that of the admin). (thumbnail not displaying) The username and path is correct, because when you click on the broken image it display's the bigger picture of the user who's logged in. Who is so kind to help me out here? Martijn Hi! I use the following PHP Session Shopping Cart (it's ready to use) Code: [Select] <? session_start(); function showCart() { $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } foreach ($contents as $id=>$qty) { $output[] = 'You have '.$qty.' items with ID: '.$id; } } else { $output[] = 'You don\'t have items in your cart'; } return join('',$output); } if(isset($_SESSION['cart'])) { $cart = $_SESSION['cart']; } else { $cart = 0; } if(isset($_GET['action'])) { $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } } $_SESSION['cart'] = $cart; echo showCart(); echo '<br/>'; echo '<a href="?action=add&id=1">Add to Cart</a>'; ?> Example of usage: === <a href="cart.php?action=add&id=1">Add to Cart</a> // Adding a new product in the cart with ID 1 <a href="cart.php?action=delete&id=1">Delete from Cart</a> // Deleting a new product in the cart with ID 1 <a href="cart.php?action=update&id=1&qty=5">Update Quantity to 5</a> // Updating the quantity of product with ID 1 === Everything is fine, but now I want to add sizes, something like: cart.php?action=add&id=1&size=XXXL. For example, the case "add" can be done like that: Code: [Select] $cart = $_GET['id'].":".$_GET['size'];.. and then the products will be saved like 1:XXXL, but then the updating and deleting will not work .. Please help me, I'm very confused how this can be done Hi, Im trying to make a shopping cart. Here is an extract while ($shoppingbasket = mysql_fetch_array($shoppingbasket2, MYSQL_ASSOC)) { echo " <form action='?' method='post'> <td><input type='text' value='$shoppingbasket[qty]' name='qty' /></td> </form> "; } The problem is if there are more than two entries in the cart so I have more than one textbox. I need each textbox assigned to the shopping cart ID to include in the WHERE cause to update the qty otherwise they all get updated the same qty. I hope this makes sences |