PHP - Quantity Drop-down Problem
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. Similar TutorialsHi 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 am following the below module, 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, 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 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. 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 } ?> 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 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. Hello, I have been searching and trying all sorts of ways to get my sub categories drop down to show the correct info after selecting a category from the main drop down but im getting stuck. It's pulling the categories and sub categories from the mysql database fine but no matter which main category i pick it keeps showing the same result in the sub category. My brother said i need to use some sort of onchange do this so the sub category list refreshs but everything i have tried doesn't work.. PLEASE could some one help. MANY MANY THANKS This is the category form Code: [Select] <select name="job_cats" style="width:165px"> <?PHP $query1 = "SELECT * FROM job_cats"; $result1 = mysql_query($query1) or die ("query 1 failed"); $count1 = mysql_num_rows($result1); for ($i = 0; $i < $count1; $i++) { $row1 = mysql_fetch_array($result1); $job_cats_title1 = $row1['title']; $job_cats_id1 = $row1['id']; echo '<option value="'.$job_cats_id1.'">'.$job_cats_title1.'</option>'; echo $job_cats_id1; } ?> </select> this would echo this in the main category list: cat1 cat2 cat3 cat4 this is the sub category form Code: [Select] <select name="job_sub_cats" style="width:165px"> <?PHP $query1 = "SELECT * FROM job_sub_cats WHERE job_cats_id = $job_cats_id1"; $result1 = mysql_query($query1) or die ("query 1 failed"); $count1 = mysql_num_rows($result1); for ($i = 0; $i < $count1; $i++) { $row1 = mysql_fetch_array($result1); $sub_cats_id1 = $row1['id']; $sub_cats_title1 = $row1['subTitle']; $cats_id1 = $row1['job_cats_id']; echo '<option value="'.$sub_cats_id1.'">'.$cats_id1.'</option>'; } ?> </select> this should echo this: 1 2 3 4 but it keeps echoing just the number 4. THANKS PLEASE HELP ricky I am creating a form that will allow the user to select the make of vehicle "FORD" for example. If that make of vehicle is selected among different makes of vehicles, then another box will appear, with all the models for that particular model "Fiesta" for example. What type of code accomplishes this setup in my web page? I do not want to list 500 models in one drop down list, but just those for each make in the first drop down list. Thanks much! Hi All, I have 2 tables: one CarMake - CarMakeID - CarMakeDesc two CarModel - CarModelID - CarModelMake - CarModelDesc Depending on what the user selects in the first dropdown (carmake) the possible selection in the second dropdown (model) needs to be limited to only the models from the selected carmake. in the second table (Carmodel : the 'CarModelMake' = CarMakeID, to identify the make) How do I limit the dropdown 'CarModel' based on the selected CarMake in the first dropdown. link : http://98.131.37.90/postCar.php code : -- -- -- Code: [Select] <label> <select name="carmake" id="CarMake" class="validate[required]" style="width: 200px;"> <option value="">Select CAR MAKE...</option> <?php while($obj_queryCarMake = mysql_fetch_object($result_queryCarMake)) { ?> <option value="<?php echo $obj_queryCarMake->CarMakeID;?>" <?php if($obj_queryCarMake->CarMakeID == $CarAdCarMake) { echo 'selected="selected"'; } ?> > <?php echo $obj_queryCarMake->CarMakeDesc;?></option> <?php } ?> </select> </label> <label> <select name="carmodel" id="CarModel" class="validate[required]" style="width: 200px;"> <option value="">Select MODEL...</option> <?php while($obj_queryCarModel = mysql_fetch_object($result_queryCarModel)) { ?> <option value="<?php echo $obj_queryCarModel->CarModelID;?>" <?php if($obj_queryCarModel->CarmodelID == $CarAdCarModel) { echo 'selected="selected"'; } ?> > <?php echo $obj_queryCarModel->CarModelDesc;?></option> <?php } ?> </select> </label> I'm a novice.. and appreciates all the help ! Hello, I'm trying to use a dropdown to display different divs. <html> <head> <title>DDlist Div Display</title> <script type="text/javascript"> function ShowDivArea(info) { var sel = document.getElementById('divArea').getElementsByTagName('div'); for (var i=0; i<sel.length; i++) { sel.style.display = 'none'; } if (info == '0') { return; } document.getElementById('divArea'+info).style.display = 'block'; } </script> <style type="text/css"> .divArea { display:none; height:100px; width:200px; border:1px solid red; } </style> </head> <body> <select id="DDDivList" onchange="ShowDivArea(this.selectedIndex)"> <option value="0" selected> -- Select A Design Service --</option> <option value="1"> QR Bookmark </option> <option value="2"> Twitter </option> <option value="3"> Ning or Tumblr </option> <option value="4"> Flyers </option> <option value="5"> Business Card or Brochure</option> <option value="6"> Album or Mixtape cover</option> <option value="7"> Other</option> </select> <div id="divArea"> <div id="divArea1" class="divArea"> <h1>QR Bookmarks</h1> <form action='qrgen.php' method='POST'> <input type='text' name='bmarksite'> URL<br> <input type='text' name='sitedesc'> Description<br> <input type='submit' value='Convert'><br> <?php include("QrCodes.php") ?> <?php $bmarksite = $_POST['bmarksite']; $sitedesc = $_POST['sitedesc']; if ($sitedesc&&$bmarksite) { $qrcode = new QrCodes; $qrcode -> IsImage =1; echo $qrcode -> GetBookmark("$bmarksite","$sitedesc"); echo "</br>"; echo $bmarksite; echo "</br>"; print $sitedesc; } else { echo "Please fill in all the required fields."; } ?> </div> <div id="divArea2" class="divArea">Twitter</div> <div id="divArea3" class="divArea">Ning or Tumblr</div> <div id="divArea4" class="divArea">Flyers</div> <div id="divArea5" class="divArea">Business Card or Brochure</div> <div id="divArea6" class="divArea">Album or Mixtape Cover</div> <div id="divArea7" class="divArea">Other</div> </div> </body> </html> The problem is with this line: <form action='qrgen.php' method='POST'>. I am using a wordpress page template. What should I change the qrgen.php to? Or how do I get it to work? Thank you for your help. Hi all, ive just coded a new thing for my website which lets users upgrade there car to a certain speed, its all coded and works fine, but im just not sure how todo one thing on it. <?php $getall = mysql_query("SELECT car, id FROM garage WHERE owner='$username'"); while($row = mysql_fetch_array($getall)){ echo $row['car']. " - ". $row['id']; echo "<br />"; } ?> That bit of my code, select the car and the car ID from my table garage, but i'm wanting it in a drop down box which shows all the cars in there garage, but not sure how I would do this. Any advice? Thanks. hi how do i get the id value from the dropdown selection from the database Here is my code. i need the id to store it another table to refer it in my application. its like a categories and subcategories table. <html> <form id="name" action="<?php $_POST['SERVER_SELF'] ?>" method="POST" > <input type="text" name="name1"> <br> <select name="select"> <?php mysql_connect('localhost','root','') or die('Could not connect to mysql ' . mysql_error()); // error message mysql_select_db("dbtest") or die(mysql_error()); $query = "select name,id from main"; $result = mysql_query($query); if ($query) { while ($row = mysql_fetch_array($result)) { $strB=$row['name']; ?> <option value="<?php $stra ?>"><?php echo $strB ?></option> <br> <?php } } ?> </select> <input type="text" name="name2"> <br> <input type="submit" name="submit1"> </form> <?php if(isset($_POST['submit'])) { //$name=$_POST['val']; $strB=$stra; mysql_connect('localhost','root','') or die('Could not connect to mysql ' . mysql_error()); // error message mysql_select_db("dbtest") or die(mysql_error()); $query = "insert into sub (sub) values('$strB')"; $result = mysql_query($query); if ($query) { echo "query executed"; } } ?> </html> thanks Hi all, ive got a script ive finishing coding from the other day, but ive got a slight problem with it. <?php if ($fetch->missions == "4"){ // Mission 4, Toyota Aygo up to 500MPH $car = "Toyota Aygo"; if ($garage->car == $car && $garage->mph == "500"){ $rightcar = "Yes"; }else{ $rightcar = "No"; } if (strip_tags($_POST['submit'])){ if ($rightcar == "Yes"){ echo ("<table width='30%' cellpadding='0' align='center' cellspacing='0' border='1' class='table'> <tr> <td class='header' align='center'>Well Done!</td> </tr> <tr> <td>You Successfully Completed Mission 3!</td> </tr> </table><br />"); $newmoney = $fetch->money + 70000000; $newrep = $fetch->rep + 750000; mysql_query ("UPDATE users SET money='$newmoney' WHERE username='$username'"); mysql_query ("UPDATE users SET rep='$newrep' WHERE username='$username'"); mysql_query ("UPDATE users SET missions='5' WHERE username='$username'") or die ("Error - Query : Line 121 : " . mysql_error()); mysql_query ("INSERT INTO `inbox` ( `id` , `to` , `from` , `message` , `date` , `read` , `saved` , `event_id` ) VALUES ( '', '$username', 'System', 'Well done! <br /> As You completed Mission 4 Successfully we will reward you with<br /> £70,000,000 Money<br /> 750,000 Rep!', '$date', '0', '0', '0' )"); } } } // Mission 4 ?> <?php if ($fetch->missions == "4"){ ?> <form action="" method="POST" name="mission4"> <table width="50%" cellpadding="0" cellspacing="0" border="1" class="table" align="center"> <tr> <td class='header' align='center'>Mission 4</td> </tr> <tr> <td>Now SD Stars can now see your progressing, they have asked you if you can get a Toyota Aygo up to 500MPH. You must get it to them without any damage to prove your werthy!</td> </tr> <tr> <td align='center' class='header'>Select Your Car:</td> </tr> <tr> <td><select class="dropbox"> <option selected>Pick Car</option> <?php $get=mysql_query("SELECT * FROM garage WHERE owner='$username' AND car='Toyota Aygo' AND mph='500'"); while($stats=mysql_fetch_object($get)){ echo "<option value=?carname=$stats->id>$stats->car, $stats->damage%, $stats->mph MPH</option>"; } ?></select></td> </tr> <tr> <td class='omg'><input type="submit" name="submit" class="button" value="Send Car!"></td> </tr> </table> </form> <?php } ?> I blive it works apart from the Drop Down Box. It selects all the cars its suppose to but when I pick the car and press submit it just basicly refreshes the page :S. I'm not sure why its doing it . Can any one else see the problem? Thanks for any help given The code for the drop down: Code: [Select] echo '<select name="select" ONCHANGE="goto(this.form)">'; while ($dropDown > 0) { if ($page == $dropDown) { $selected = 'selected="selected"'; } else { $selected = ""; } echo "<option value=\"searchFlights.php?page=" . $dropDown . "\" $selected>" . $dropDown . "</option>"; $dropDown = $dropDown - 1; } echo '</select>'; It works fine, but I want 1 to be at the top of the list and go down from there because right now, it starts with the biggest number and goes down. Any suggestions? Thanks! Hello, must admit i'm very new to this and just a hobiest , I am creating a page which will be used for logging information. With a mysql database i have two tables "tbl_rides" & "tbl_courses" rides is the main table for storing information and has a foreign key associating column "course_id" with course_id in the tbl_courses What i want to do on a HTML/PHP page is display a drop down box that has the contents of "course" from the tbl_courses but when the user selects it and submits the record is written to the main form "tbl_rides" "course_id" so display the friendly name via the foreign key but the record is written to "tbl_rides" Can that be done .. am i going about this wrong ?
Thanks for any help Andrew. trying to get my drop down box to display more then one result. I have two users with Mod wrote in the column Monitor but right now it only displays just the one. So I need to display all the goaulds that have mod in the monitor column <?php Code: [Select] $result = mysql_query("SELECT goauld FROM users WHERE monitor ='mod' ORDER BY id DESC") or die(mysql_error()); while($row = mysql_fetch_array( $result )) { if($row['goauld'] == $_POST['name_list']){ echo '<div class="containerc">'; echo '<div class="search">'; echo '<form method="post" >'; echo '<select name="name_list" class="textbox" id="name_list">'; echo "<option value=\"".$row['goauld']."\">".$row['goauld']."</option>"; echo "<option selected=\"selected\" value=\"".$row['goauld']."\">".$row['goauld']."</option>"; echo '</select>'; echo '<input type="submit" name="remove" id="remove" value="Remove">'; } } } '</form>'; '</div>'; '</div>'; ?> im fairly new to php so tend to do trial and error..... more error than trial tbh. im wondering if it is possible to get a drop down menu to fill from a mysql database and to arrange it alphabetically. i have created the menu just dont know how to arrange it better. also how can i use the items id in drop menu to load other info from that row on the database. hope you can help me. Code: [Select] <FORM> <?php $result = mysql_query( "SELECT * FROM movie_info" ) ; echo "<select name= film onChange='submit()' >film name</option>"; while ($nt=mysql_fetch_array($result)){ ?> <?php echo "<option value='$nt[id]'>$nt[title] </option>"; } ?> </select> </FORM> Hi. I have drop down boxes for date and time that work. The year is a problem because I am using variables instead of fixed values. Code: [Select] <select name="Year" style="width:60px"> <option value="2010" >Test <option value="<?=$ThisYear?>" <? if ($Year == "<?=$ThisYear?>"){?> SELECTED <?}?> ><?=$ThisYear?> <option value="<?=$NextYear?>" <? if ($Year == "<?=$NextYear?>"){?> SELECTED <?}?> ><?=$NextYear?> </select> <select name="Hour" style="width:50px"> <option value="10" <? if ($_SESSION["Hour"] == "10"){?> SELECTED <?}?> >10 <option value="11" <? if ($_SESSION["Hour"] == "11"){?> SELECTED <?}?> >11 <option value="12" <? if ($_SESSION["Hour"] == "12"){?> SELECTED <?}?> >12 <option value="13" <? if ($_SESSION["Hour"] == "13"){?> SELECTED <?}?> >13 <option value="14" <? if ($_SESSION["Hour"] == "14"){?> SELECTED <?}?> >14 <option value="15" <? if ($_SESSION["Hour"] == "15"){?> SELECTED <?}?> >15 <option value="16" <? if ($_SESSION["Hour"] == "16"){?> SELECTED <?}?> >16 <option value="17" <? if ($_SESSION["Hour"] == "17"){?> SELECTED <?}?> >17 <option value="18" <? if ($_SESSION["Hour"] == "18"){?> SELECTED <?}?> >18 <option value="19" <? if ($_SESSION["Hour"] == "19"){?> SELECTED <?}?> >19 <option value="20" <? if ($_SESSION["Hour"] == "20"){?> SELECTED <?}?> >20 </select> however this works Code: [Select] <select name="Year" style="width:60px"> <option value="2010" >Test <option value="<?=$ThisYear?>" <? if ($Year == "2011"){?> SELECTED <?}?> ><?=$ThisYear?> <option value="<?=$NextYear?>" <? if ($Year == "2012"){?> SELECTED <?}?> ><?=$NextYear?> </select> Can anyone help with this please TIA Desmond. |