PHP - How To Achieve Addtocart Without Quantity?
I am following the below module, Similar TutorialsHi, I have table called done in mysql and there is a row which is filled with the users id and another row with todays date. Now what I want to know which three users participated the most with filling out stuff on the website according to todays date. For instance First user filled out 5 2nd user filled out 3 3rd user filled out 2 You get the idea. I dont know what type of query should I write to extract the data based on the users id and how many times they participated on the particular day. Another example of the table is 1st column user id = 20 time= todays date 2nd column user id= 20 time = todays date Showing the user participated twice on the day. Thanks any help is appreciated. I was thinking of ways I could use use PHP to make an iframe dissapear when the user has clicked the submit button in the iframe. I was thinking there is probably no way to tell if the user has submitted the form in the iframe? I tried using unset(), with the iframe code being a variable. I echoed the iframed form, and placed a submit button below the iframe. When the user is done with the iframe form, they click the submit button below it and it will dissapear. Ive done that, but I was wondering would it be possible at all to make the frame dissapear once the user has clicked the submit button IN the iframe? If not possible with PHP maybe javascript? IDK, suggestions would be appreciated. Thanks In my database is a field for qty(quantity). I have the form with qty as a drop down, but I only want whatever is in the database to show in the drop down. For example, if there are only 5 of a particular item in the database, I only want the user to be able to select up to 5 qty, and if there are only 2, I only want them to be able to select 2 as the qty. How do I go about doing this? I have my size drop down like this Code: [Select] <select name="size"> <?php foreach ($size as $value) { ?> <option value="<?php echo $value;?>"><?php echo $value;?></option> <?php } ?></select> But since the values are stored like sm,med,lg that's pretty simple to do. I tried foreach, but since it's just a number, there is only 1 number, and I am at a total lost with this one. Thank you in advance. Hello this may sound a little confusing.
I recently made a fake website using this phpacademy tutorial I found. Anyways it has an quantity stock what I mean by this is let's I have 3 copies of a video game an a person set they quantity for 2 of the 3 copies and proceed to the checkout through paypal payment successful okay. My question is: How can I go about sending the quantity stock back to the database to subtract 2 from 3 to be left with 1 copy of the game in the quantity section after a successful purchase? Code is below in case I confused someone ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Maximumize / calling the quantity from Database ///////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if(isset($_GET['add'])){ $quantity = mysqli_query($db_conx,'SELECT id, quantity FROM products WHERE id='.mysqli_real_escape_string($db_conx,(int)$_GET['add'])); while ($row = mysqli_fetch_assoc($quantity)){ if ($row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]) { $_SESSION['cart_'.(int)$_GET['add']]+='1'; } } header('Location: '.$page); } if(isset($_GET['remove'])){ $_SESSION['cart_'.(int)$_GET['remove']]--; header('Location:' .$page); } if(isset($_GET['delete'])){ $_SESSION['cart_'.(int)$_GET['delete']]='0'; header('Location:' .$page); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Calling all products from Database ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function products($db_conx){ $get = mysqli_query($db_conx,"SELECT id, name, description, price FROM products WHERE quantity > 0 ORDER BY id DESC"); if (mysqli_num_rows($get) ==0){ echo "There are no products to display"; } else { while ($row = mysqli_fetch_assoc ($get)){ echo '<p>'.$row ['name']. '<br/> <br/>' .$row ['description']. '<br/> <br/>' .'$'.number_format($row['price'], 2).' <a href="cart.php?add='.$row ['id'].'">Add</a></p>'; } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Paypal Checkout ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function paypal_items($db_conx){ $num = 0; foreach($_SESSION as $name => $value){ if ($value != 0){ if(substr($name, 0, 5)=='cart_'){ $id = substr($name, 5, strlen($name) -5); $row = mysqli_query($db_conx,'SELECT id, name, price, shipping FROM products WHERE id ='.mysqli_real_escape_string($db_conx,(int)$id)); while ($query = mysqli_fetch_assoc($row)){ $num++; echo '<input type="hidden" name="item_number_'.$num.'" value="'.$id.'">'; echo '<input type="hidden" name="item_name_'.$num.'" value=" '.$query['name'].' ">'; echo '<input type="hidden" name="amount_'.$num.'" value=" '.$query['price'].' ">'; echo '<input type="hidden" name="shipping_'.$num.'" value=" '.$query['shipping'].' ">'; echo '<input type="hidden" name="quantity_'.$num.'" value=" '.$value.' ">'; } } } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Shopping Cart View ///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function cart($db_conx) { foreach($_SESSION as $name => $value) { if ($value > 0) { if(substr($name,0 ,5) . 'cart_'){ $id = substr($name, 5, (strlen($name) -5)); $row = mysqli_query($db_conx,'SELECT id, name, price FROM products WHERE id=' .mysqli_real_escape_string ($db_conx,(int)$id)); while ($query = mysqli_fetch_assoc($row)){ $sub = $query['price']*$value; echo $query['name'].' x ' .$value. ' @ $' .number_format ($query['price'], 2). ' = $'.number_format($sub, 2). '<a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'">[Delete]</a> <br/> <br/> '; } } $total += $sub + $shipping; } } if ($total ==0) { echo "Your cart is empty."; } else { echo 'Total: $' .number_format($total, 2); ?> <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="upload" value="1"> <input type="hidden" name="business" value="youremail@outlook.com"> <?php paypal_items($db_conx); ?> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="amount" value="<?php echo $total ;?>"> <input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!"> </form> <?php } } ?> Edited by mac_gyver, 09 September 2014 - 08:06 PM. code tags please Hi All This is not really somthing the paypal developers answer as its general php so thought I would ask on here Basically, have 3 products with 3 item numbers (101,102,103) I have set up if, elseif statements to insert into database depending on the item number. This works fine. However i now want to integrate the quantity. As the purchase will set up a user, i want the inserts to be dependent on the quantity purchased, so if 3 courses are purcased under item number 101 then it sets up 3 user accounts (inserts in to users x3) with the username with an increment of for example test@test.com-1 Can someone pointe me in the correct direction please? Here is the script(including the mail script at bottom but ignore) Code: [Select] $fecha = date("m")."/".date("d")."/".date("Y"); $fecha = date("Y").date("m").date("d"); //check if transaction ID has been processed before $checkquery = "select txnid from paypal_payment_info where txnid='".$txn_id."'"; $sihay = mysql_query($checkquery) or die("Duplicate txn id check query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); $nm = mysql_num_rows($sihay); if ($nm == 0){ //execute query if ($itemno == "101"){ $strQuery = " INSERT INTO `users` ( `id` , `firstname` , `lastname` , `company` , `address1` , `address2` , `address3` , `postcode` , `email` , `username` , `password` , `wsiosh` , `msiosh` , `nebosh` , `telephone` ) VALUES ('' , '".$first_name."', '".$last_name."', '".$business."', '".$address_street."', '".$address_city."','', '".$address_zip."', '".$payer_email."', '".$payer_email."', '".$passwordnew."', 'yes', '', '', '' )"; $result = mysql_query($strQuery) or die("Cart - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); for ($i = 1; $i <= $num_cart_items; $i++) { $itemname = "item_name".$i; $itemnumber = "item_number".$i; $on0 = "option_name1_".$i; $os0 = "option_selection1_".$i; $on1 = "option_name2_".$i; $os1 = "option_selection2_".$i; $quantity = "quantity".$i; $struery = "insert into `paypal_payment_info`(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,mc_gross,mc_fee,itemnumber,itemname,os0,on0,os1,on1,quantity,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$item_number."','".$item_name."','".$option_name1."','".$option_selection1."','".$option_name2."','".$option_selection2."','".$quantity."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')"; $result = mysql_query($struery) or die("Cart - paypal_cart_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); } } else if ($itemno == "102"){ $strQuery = " INSERT INTO `users` ( `id` , `firstname` , `lastname` , `company` , `address1` , `address2` , `address3` , `postcode` , `email` , `username` , `password` , `wsiosh` , `msiosh` , `nebosh` , `telephone` ) VALUES ('' , '".$first_name."', '".$last_name."', '".$business."', '".$address_street."', '".$address_city."','', '".$address_zip."', '".$payer_email."', '".$payer_email."', '".$passwordnew."', '', 'yes', '', '' )"; $result = mysql_query($strQuery) or die("Cart - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); for ($i = 1; $i <= $num_cart_items; $i++) { $itemname = "item_name".$i; $itemnumber = "item_number".$i; $on0 = "option_name1_".$i; $os0 = "option_selection1_".$i; $on1 = "option_name2_".$i; $os1 = "option_selection2_".$i; $quantity = "quantity".$i; $struery = "insert into `paypal_payment_info`(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,mc_gross,mc_fee,itemnumber,itemname,os0,on0,os1,on1,quantity,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$item_number."','".$item_name."','".$option_name1."','".$option_selection1."','".$option_name2."','".$option_selection2."','".$quantity."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')"; $result = mysql_query($struery) or die("Cart - paypal_cart_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); } } else if ($itemno == "103"){ $strQuery = " INSERT INTO `users` ( `id` , `firstname` , `lastname` , `company` , `address1` , `address2` , `address3` , `postcode` , `email` , `username` , `password` , `wsiosh` , `msiosh` , `nebosh` , `telephone` ) VALUES ('' , '".$first_name."', '".$last_name."', '".$business."', '".$address_street."', '".$address_city."','', '".$address_zip."', '".$payer_email."', '".$payer_email."', '".$passwordnew."', '', '', 'yes', '' )"; $result = mysql_query($strQuery) or die("Cart - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); for ($i = 1; $i <= $num_cart_items; $i++) { $itemname = "item_name".$i; $itemnumber = "item_number".$i; $on0 = "option_name1_".$i; $os0 = "option_selection1_".$i; $on1 = "option_name2_".$i; $os1 = "option_selection2_".$i; $quantity = "quantity".$i; $struery = "insert into `paypal_payment_info`(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,mc_gross,mc_fee,itemnumber,itemname,os0,on0,os1,on1,quantity,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$item_number."','".$item_name."','".$option_name1."','".$option_selection1."','".$option_name2."','".$option_selection2."','".$quantity."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')"; $result = mysql_query($struery) or die("Cart - paypal_cart_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); } } // send an email in any case echo "Verified"; mail($notify_email, "VERIFIED IPN", "$res\n $req\n $strQuery\n $struery\n $strQuery_2"); } else { // send an email mail($notify_email, "VERIFIED DUPLICATED TRANSACTION", "$res\n $req \n $strQuery\n $struery\n $strQuery_2"); } //subscription handling branch if ( $txn_type == "subscr_signup" || $txn_type == "subscr_payment" ) { // insert subscriber payment info into paypal_payment_info table $strQuery = "insert into paypal_payment_info(paymentstatus,buyer_email,firstname,lastname,street,city,state,zipcode,country,mc_gross,mc_fee,memo,paymenttype,paymentdate,txnid,pendingreason,reasoncode,tax,datecreation) values ('".$payment_status."','".$payer_email."','".$first_name."','".$last_name."','".$address_street."','".$address_city."','".$address_state."','".$address_zip."','".$address_country."','".$mc_gross."','".$mc_fee."','".$memo."','".$payment_type."','".$payment_date."','".$txn_id."','".$pending_reason."','".$reason_code."','".$tax."','".$fecha."')"; $result = mysql_query($strQuery) or die("Subscription - paypal_payment_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); // insert subscriber info into paypal_subscription_info table $strQuery2 = "insert into paypal_subscription_info(subscr_id , sub_event, subscr_date ,subscr_effective,period1,period2, period3, amount1 ,amount2 ,amount3, mc_amount1, mc_amount2, mc_amount3, recurring, reattempt,retry_at, recur_times, username ,password, payment_txn_id, subscriber_emailaddress, datecreation) values ('".$subscr_id."', '".$txn_type."','".$subscr_date."','".$subscr_effective."','".$period1."','".$period2."','".$period3."','".$amount1."','".$amount2."','".$amount3."','".$mc_amount1."','".$mc_amount2."','".$mc_amount3."','".$recurring."','".$reattempt."','".$retry_at."','".$recur_times."','".$username."','".$password."', '".$txn_id."','".$payer_email."','".$fecha."')"; $result = mysql_query($strQuery2) or die("Subscription - paypal_subscription_info, Query failed:<br>" . mysql_error() . "<br>" . mysql_errno()); mail($notify_email, "VERIFIED IPN", "$res\n $req\n $strQuery\n $struery\n $strQuery2"); } } // if the IPN POST was 'INVALID'...do this else if (strcmp ($res, "INVALID") == 0) { // log for manual investigation mail($notify_email, "INVALID IPN", "$res\n $req"); } } fclose ($fp); } ?> <?php // read the post from PayPal system and add 'cmd' $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } // post back to PayPal system to validate $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; // If testing on Sandbox use: // $header .= "Host: www.sandbox.paypal.com:443\r\n"; $header .= "Host: www.paypal.com:443\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; // If testing on Sandbox use: //$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); // assign posted variables to local variables $item_name = $_POST['item_name']; $item_number = $_POST['item_number']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; $payment_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; //set email variables $From_email = "From: xxx; $Subject_line = "Your Purchase fxxx"; $email_msg = "To $payer_email, Thank you for your purchase of $item_name. You are now able to log in using details below: User: $payer_email Password : password Log in to your account using the link below and change your password as soon as possible. You can purchase more courses by visiting your profile page Kind Regards "; $email_msg .= "\n\nThe details of your order are as follows:"; $email_msg .= "\n\n" . "Transaction ID: " . $txn_id ; $email_msg .= "\n" . "Payment Date: " . $payment_date; if (!$fp) { // HTTP ERROR } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { // check the payment_status is Completed // check that txn_id has not been previously processed // check that receiver_email is your Primary PayPal email // check that payment_amount/payment_currency are correct // process payment $mail_From = $From_email; $mail_To = $payer_email; $mail_Subject = $Subject_line; $mail_Body = $email_msg; mail($mail_To, $mail_Subject, $mail_Body, $mail_From); } else if (strcmp ($res, "INVALID") == 0) { // log for manual investigation $mail_From = $From_email; $mail_To = $receiver_email; $mail_Subject = "INVALID IPN POST"; $mail_Body = "INVALID IPN POST. The raw POST string is below.\n\n" . $req; mail($mail_To, $mail_Subject, $mail_Body, $mail_From); } } fclose ($fp); } I have a form which has both radio buttons and textfields. Each individual radio button is associated with a form field. For this example, lets say the Radio button references a tool name and the form field represents a quantity, or number of tools needed for a certain job. So the form would look as follows: Quote o Some Tool Quantity ___ (<-- lets pretend thats a form field) The question is, how would I go about adding the tool and quantity to the same row in the database if I am creating a new row? The simple way would be have each radio button and quantity be its own entity in the HTML. For example: Code: [Select] <input name="tool1" type="radio" value="Hammer" /> <input name="tool_quantity1" type="text" /> <input name="tool2" type="radio" value="Wrench" /> <input name="tool_quantity2" type="text" /> However easy this method may be, and however functional it may work, it is not how I wish to achieve this because we are talking maybe 100 tools. I think it would be easier using some kind of loop function that goes through an array of anything that has some form of data stored in it. For example, instead of the code being the above, I would like to change it to the following: Code: [Select] <input name="tools[]" type="radio" value="Hammer" /> <input name="tools_quantity[]" type="text" /> I understand the basic foreach function Code: [Select] foreach ($_POST['tools'] as $someVariableName) { //do some stuff } But I don't understand how I can get the value of 2 different form fields and have them associated with one another. I want the tool and the quantity of tools to be stored in the same row. How is this done? Is this even possible using a loop function like foreach or while? Please help! As always, any help would be greatly appreciated!! Bl4ck Maj1k There are two effects that I have seen on website and keep wondering how they have been achieved. The first is when you go on Facebook and you type a link into your status bar. Then Facebook will automatically get some information about that article. The second effect is something I have seen on twitter and other websites. If you scroll down to the bottom of the page it will detect this and then load more content. If anyone could link me to any article or tutorials explain how these effects have been done that would be great. Thanks for any help. Hi, could you please help me with an issue? I want to hide the price for one product in the WooCommerce emails that I send to the clients Only If the quantity of a product is over 50. For all the other items I want the price to be shown. For example, the order has 2 products, one with 30pcs quantity that displays price, and the other with 120pcs quantity but with a text 'some text' instead of the price. I modified the email-order-items.php, <?PHP echo $order->get_formatted_line_subtotal($item); ?> But, It's not working. I'm sure is this line but I don't know how to continue and I'm stuck. Thank you so much. Edited July 16, 2020 by wpdevModified information Hi, what i am after is for instance, the user is viewing my website. He is in a different section on my website and there is a sign in button. The user goes to the sign in page, now what i want is when the user logs in, the user to be redirected back to the section which he was viewing before signing in. Basically in more clear words, I want the user to return to the content he was viewing after logging in. Hello all, I'm looking for some advice on a problem. I have a very basic web page containing three section, the header, the content and the footer in that order. What I would like is the header and footer always on the page and only the content section change by means of links in a navigation bar. I've looked into iframes, php include, javascript and something called Ajax and must say I'm all a bit confused by it all. Which would be most advisable and how would I excecute it. My pages are as follows. Home page is. index.php Pages I would like to show in the content Div. about.php contact.php home.php If you need any more information, please let me know. Thank you in advance for your help. In my shopping cart i want an alert message when the maximum number of 5 for the item has been reached or ask them to delete the item if the press - when the item quantity is at 1.
i have it working in php:
//add to quantity of item if (isset($_POST['itemadd'])){ $additem = $_POST['additem']; $sqladd = "SELECT quantity FROM orders WHERE id = '$additem'"; $query_add = mysqli_query($db_conx, $sqladd); while($row = mysqli_fetch_array($query_add, MYSQLI_ASSOC)){ $itemqty = $row['quantity']; if ($itemqty < 5){ $addqty = $itemqty + 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"; } }But rather than display the message in a div i would like a javascript alert box to pop up, i tried the following code: <script type="text/javascript"> function CheckQtyPlus(){ var qty = '<?php echo $qty; ?>'; alert("message here"+qty); } </script>but i get the same quantity number for every item in the cart, i had this error with the php update but i got round that by querying sql to give me the quantity of an item by the items id. can the same thing be done in javascript / ajax? $qty by the way is referenced earlier in the script to get information for the cart table to display items. thanks Michael Thanks to the help of user Winstons on another post I've managed to almost finished this bit of code. I thought I would move it over because the other subject doesn't explain the new problem that's occured. Basically it's a shopping cart with contains both the id of selected items and the selected size in a session. Everything is stored like this 12s3,6s1 etc. Where 12 and 6 are the item ids and then 3 and 1 are the selected size of that item. In the code below when I do: <?php echo 'ID ' . $val[0] . '; Size: ' . $val[1] . '<br/>'; ?> Each of the items and their accompanying size is echoed out perfectly. However if there are two of 12s3 is would need to recognise that and change the quantity ($qty) to 2, rather than display the same item twice. Here is my code. Any help would be great. 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[$item])) ? $contents[$item] + 1 : 1; echo '<form action="basket.php?action=update" method="post">'; echo '<table>'; foreach ($data as $id=>$qty) { $sql = "SELECT * FROM store WHERE id LIKE '$id' AND live LIKE '0'"; $result = mysql_query($sql); while ($rows = mysql_fetch_array($result)) { extract($rows); ?> <li> <div id="view_basket_image"> <img src="<?php echo $rows['indeximage']; ?>" /> </div> <div id="view_basket_title"> <span class="view_basket_brand"><?php echo $rows['brand']; ?> ·</span> <span class="view_basket_description"><?php echo $rows['title']; ?></span> </div> <div id="view_basket_qty"> <input type="text" name="qty<?php echo $id; ?>" value="<?php echo $qty; ?>" size="3" maxlength="3" class="view_basket_qty" /> </div> <div id="view_basket_price"> <span class="view_basket_x">x</span>£<?php echo $rows['price']; ?> <?php /* WORK OUT ITEM WEIGHTS */ $itemweight = $rows['weight'] * $qty; $totalweight += $rows['weight'] * $qty; ?> </div> <div id="view_basket_itemtotal"> <?php $itemtotalprice = $rows['price'] * $qty; $itemtotal = number_format($itemtotalprice, 2, '.', ','); echo '£'; echo $itemtotal; $total += $rows['price'] * $qty; ?> </div> <div class="clear"></div> </li> <?php } } ?> </ul> </div> <?php } ?> Hi 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. I 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. |