PHP - Help Needed With Cart Function
I have 3 actions below which control my cart. My problem is with the minus action. It's supposed to remove 1 quantity from the cart but instead it takes the quantity all the way down to 1.
for example: you add 3 quantities of a usb stick and you want to remove 1 quantity, it would take the amount of quantity to 1 instead of 2. here are the functions: switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; header("Location: cart.php"); } else { $cart = $_GET['id']; header("Location: cart.php"); } break; case 'minus': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $item - $id; } 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; } can some help with the minus function. thanks Similar TutorialsI have a shopping cart on my website with some minor errors. When you refresh the page it adds an extra quantity to the item when it shouldn't. Any help the code is below. $cart = $_SESSION['cart']; $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; I have this function completely written in my class file that I am working on. The point to this function is to be able to check the login of a user or administrator for either of the control panels associated with my site. It will check the session intime as well as the page / module referenced. Once it passes all those checks, it will check and ensure the emailaddress/password stored in the current session still holds true and the account is still active... if the account is still active it will update the lastActivity as well as update all of the session variables with what is currently in the database. What I am looking for is basically a look at the function, see if it looks good.. If there is any part to it that could create security holes for the site just off the login function itself... Usage: $q->validUser($_SESSION['user'], $_mod); <?php function validUser($sess, $p) { if ($sess['inTime'] == '' && $p != 'login' && $p != 'logout') { session_destroy(); $login = '0'; $_int = ''; return $login; } else if ($sess['inTime'] < time()-3600 && $p != 'login') { $sess['inTime'] = ''; session_destroy(); $this->check_login($sess, $p); } else { $this->user = $sess['emailAddress']; $this->pass = $sess['password']; $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); if ($login = $this->sql_numrows($login) < 1) { $sess['inTime'] == ''; session_destroy(); $login = '0'; } else { // logged in, lets update the database for last_activity AND the session. $this->sql_query("UDATE users SET lastActivity = '".now()."' WHERE emailAddress = '".$this->user."'"); $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); $login = mysql_fetch_assoc($login); foreach ($login as $key => $value) { $sess[$key] = $value; } $sess['inTime'] = time(); $login = '1'; } return $login; } } ?> That is the main function, sql_query and sql_numrows is: <?php function sql_query($query = "", $transaction = FALSE) { unset($this->query_result); if ($query != "") { $this->num_queries++; if ($transation == BEGIN_TRANSACTION && !$this->in_transation) { $result = mysql_query("BEGIN", $this->db_connect_id); if (!$result) { return false; } $this->in_transaction = TRUE; } $this->query_result = mysql_query($query, $this->db_connect_id); } else { if ($transaction == END_TRANSACTION && $this->in_transaction ) { $result = mysql_query("COMMIT", $this->db_connect_id); } } if ($this->query_result) { unset($this->row[$this->query_result]); unset($this->rowset[$this->query_result]); if ($transaction == END_TRANSACTION && $this->in_transaction ) { $this->in_transaction = FALSE; if (!mysql_query("COMMIT", $this->db_connect_id)) { mysql_query("ROLLBACK", $this->db_connect_id); return false; } } return $this->query_result; } else { if ($this->in_transaction ) { mysql_query("ROLLBACK", $this->db_connect_id); $this->in_transaction = FALSE; } return false; } } function sql_numrows($query_id = 0) { if(!$query_id) { $query_id = $this->query_result; } return ($query_id) ? mysql_num_rows($query_id) : false; } ?> Any insight that can help to benefit these functions would be appreciated. How 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>
hello. im trying to write a function that sets the file path depending on what it pulls from the database i have 2 databases 1 called "templates" which has a list of template names with there id's and 1 called "basicSetting" which sets the active and default templates. in the template db i have id name type id1 = template1 admin id2 = template1 main id3 = template1 main in basic settings i have set activeAdminTemp_id = 1 defaultAdminTemp_id = 1 activeTemp_id = 2 defaultTemp_id = 2 the path should be something like this Code: [Select] include(SITE_ROOT.DS.'GET TYPE/templates/GET TEMPLATE FOLDER NAME'.DS.GET TEMPLATE NAME.php); SITE_ROOT = www.sitename.com/ GET TYPE = /admin or in the main root /templates/ = where the templates are stored GET TEMPLATE FOLDER NAME = the name of the template is the same as the folder name GET TEMPLATE NAME.php; = the name of the template.php this is what i have in my functions file Code: [Select] function include_templates(){ $tempBS = basicSettings::find_all(); //SHOULD GET THESE VALUES $tempBS->id."<br />"; $tempBS->activeAdminTemp_id."<br />"; $tempBS->defaultAdminTemp_id.'<br/>'; $tempBS->activeTemp_id.'<br/>'; $tempBS->defaultTemp_id.'<br/>'; $temp = Templates::find_all(); //SHOULD GET THESE VALUES $temp->id."<br />"; $temp->name."<br />"; $temp->type.'<br/>'; } now i need to add into my function something like this ... but im not sure. Code: [Select] $sql = "SELECT * FROM templates WHERE id='".$tempBS->id."'"; echo include(SITE_ROOT.DS.'.$temp->type./templates/'.$temp->name.''.DS.'temp->name.''.php'); but that i not working. please help thanks rick Hi there. I have a PHP Function like so: <?php function JomSocial_field($fieldcode) { $database=& JFactory::getDBO(); $user =& JFactory::getUser(); $userId = $user->get( 'id' ); $sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= '$fieldcode'"; $database->setQuery( $sql ); $fieldID = $database->loadResult(); $sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}"; $database->setQuery( $sql ); echo $database->loadResult(); } ?> I can then insert the results into form inputs like so: Code: [Select] <input type="hidden" id="enrolment_year" name="enrolment_year" value="<?php JomSocial_field("enrolment_year"); ?>" /> However, I now want to use the result in a variable like so <?php $filename1 = "folder/".print(JomSocial_field("enrolment_year"))."/file.zip"; but it doesn't work...it just actually prints the result as text on the page. The echo command doesn't work either. If it were an item that has been posted, I could get it using the $_POST["enrolment_year"], but the trouble is, I want to get the value on first page load, not after a post. Can anyone help me please? Hi, Since upgrading to php 5.3 i have a line of code on my site that is giving me a depreciated error. The line of code is as follows: $data=eregi_replace(">"."[[:space:]]+"."<","><",$data); I've got as far as knowing i need to change it from eregi_replace to preg_replace but i can't for the life of me work out where to put any backslashes etc, if any. Is there a formula for working this type of thing out? Every example i see has backslashes and $1's all over the place. Do i simply do this "/ and this /" after and before every double quote? Or is it not as simple as that? Things never are are they! Please could an expert on here offer me any assistance. This is an important line of code(i think) so i didn't want to experiment as i would normally do, i need to get this right first time as i don't know what will happen if i get this wrong. Cheers. ok im making a shooping cart how do i make it so it remembers that items people add to the 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> 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 } ?> 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 Can someone give me name of free shopping cart with auctions(offers) like Open Classifieds ? 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. 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; } 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. 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? 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 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> |