I have a form in my PHP page which is created by a loop through an array.
echo '<form method="POST" name="add_to_cart_form">
<div id="Product_add_sizes">
<table border="0" cellpadding="2" class="product_txt_font" align="center">
<input type="hidden" name="product_id" value="'.$arr_get_products[$c]['id'].'">';
for ($d = 0; $d < count($arr_get_product_details); $d++)
{
echo '<tr>
<td>
<input type="radio" name="size[]" value="'.$arr_get_product_details[$d]['size'].'">
</td>
<td>
<input class="qty" type="text" size="3" name="amount" value="1">
</td>
</tr>';
}
echo '</table>
<input type="submit" name="add_to_chart" value="Add Product" />
</div>
</form>';
Now when I post this form, I'm searching for a way to get the input of qty which belongs to the selected radio button. I only need the data from the selected radio button row. The other data is not needed as I want to add this product to a shopping cart array.
if (isset($_POST['add_to_chart']))
{
$product_id = $_POST['product_id'];
$size = $_POST['size'][0];
$qty = $_POST['amount'];
}
When posting the page, I know what size is wanted cause of the size[]
array but I can't get the related qty value that matches the selected radio button.
I've tried to treat the qty the same way as the radio button by making it an array qty[] but that will return me all values.
I've search SO and googled a bunch but haven't found a decent answer, but It looks to me that this is used a lot. Please let me know what i'm missing here.
Any help is greatly appreciated!
Radio buttons should all use the same name. Only the selected radio button value is submitted:
<input type="radio" name="Radiosize" value="'.$arr_get_product_details[$d]['size'].'">
then:
$size = $_POST['Radiosize'];
There is no need to look at it as an array - it isn't submitted as one. Radio Buttons are not like checkboxes in form processing.
change
<input class="qty" type="text" size="3" name="amount" value="1">
to
<input class="qty" type="text" size="3" name="amount[]" value="1">
and then you will have 2 arrays that will have same size.
<?php
$size = $_POST['size'][0];
$amount = $_POST['amount'][$size];
?>
Form code:
<input type="radio" name="size" value="'.$arr_get_product_details[$d]['size'].'">
<input class="qty" type="text" size="3" name="amount['.$arr_get_product_details[$d]['size'].']" value="1">
And then you will have value of size. And array of amounts with size keys.
$size = $_POST['size'];
$amount = $_POST['amount'][$size];
I solved the issue by doing the following.
The guys above here all got me on the right track and couldn't have done it without them!
Changed
<input type="radio" name="size[]" value="'.$arr_get_product_details[$d]['size'].'">
<input class="qty" type="text" size="3" name="amount" value="1">
To
<input type="radio" name="size['.$d.']" value="'.$arr_get_product_details[$d]['size'].'">
<input class="qty" type="text" size="3" name="amount['.$d.']" value="1">
Also changed
if (isset($_POST['add_to_chart']))
{
$product_id = $_POST['product_id'];
$size = $_POST['size'][0];
$qty = $_POST['amount'];
}
To this
if (isset($_POST['add_to_chart']))
{
// Array ID key
$key = key($_POST['size']);
$product_id = $_POST['product_id'];
$size = $_POST['size'][$key];
$qty = $_POST['amount'][$key];
}
Works like a charm! Thank you all for your very helpful comments!
Related
I have a form that allows members to click a (+) sign, and it will put another form field there. They can do this to basically without limit.
The problem I have is if they do it, let's say, 3 times and fill out all 3, when I get the data to save it, it's placing the first field in the database and not the others.
Here is my code:
Here is the JavaScript that makes the div show as they push the (+) sign.
<script type="text/javascript">
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
document.getElementById('newlink').appendChild(div1);
}
</script>
<style>
.feed {padding: 5px 0}
</style>
This is part of the form that does the above...
<td width="50%" valign="top">
<div id="newlink">
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
<hr>
<p id="addnew">
+ Click Here To Add Another Biz/Traffic/Tools Site
</p>
<div id="newlinktpl" style="display:none">
<hr>
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
This is the part of the PHP code that would save it...
$i=0;
$linkname = $_POST["recname"][0];
while($linkname != ""){
$linkname = $_POST["recname"][$i];
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
$linkname = $res->real_escape_string($linkname);
$linkurl = $res->real_escape_string($linkurl);
$linktype = $res->real_escape_string($linktype);
$result299 = mysqli_query($res, "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')");
$i++;
}
It's all working except that is does not store all the data in the database (only the first one saves). That's the part I need help with please.
Please explain what I have done wrong and how to get it to store all the fields in the database, no matter how many the user creates and fills out.
I tested your code and it works fine so far if I use it like this:
$i=0;
$linkname = $_POST[recname][0];
while($linkname != ""){
$linkname = $_POST[recname][$i];
$linkurl = $_POST[reclink][$i];
$linktype = $_POST[rectype][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
There's no information about the $res object you're calling real_escape_string() on, so I'll just skip that for now. There are a couple of weaknesses in the code though:
You are referencing the post keys with barenames instead of strings.
PHP will gracefully assume you meant it as a string, but it will trigger a notice like Use of undefined constant recname - assumed 'recname'. Enclose them in quotes to make it clean.
Your use of the loop will result in an empty element inserted in the database every time.
You set the new linkname AFTER checking if $linkname is empty, but the variable contains the name of the last iteration. Instead, do something like this:
$i=0;
while($linkname = $_POST["recname"][$i]){
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
Your code only allows for one radio button to be checked at a time
You cannot use rectype[] as a name for radio buttons, as an equal name forms a group of radio buttons out of all the elements. You need to name them like this:
<input type="radio" name="rectype[0]" value="1"> Business Opp<br />
<input type="radio" name="rectype[0]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[0]" value="3"> Tools Site<br />
<input type="radio" name="rectype[1]" value="1"> Business Opp<br />
<input type="radio" name="rectype[1]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[1]" value="3"> Tools Site<br />
and so on. You can do that programatically in your javascript code like this:
<script type="text/javascript">
var counter = 1;
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
var inputs = div1.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
if (inputs[i].type == "radio") {
inputs[i].name="rectype[" + counter + "]";
}
}
counter++;
document.getElementById('newlink').appendChild(div1);
}
</script>
That said, I don't see why it should only save one item, unless you have a key constraint hitting or something else we cannot assume from the piece of code you shared.
I'm building a sort of php shop that will allow a user to enter amounts for various products and then a form will process the order. There is no payment processing etc. What I am struggling to do is add each product to each amount to send through to the order form as a $_POST variable. Currently my ordered items are a standard form:
<input type="text" id="value" name="ordered-items[]" />
I thought I could add the product ID as a hidden variable, but that will just add it for every product.
<input type="hidden" id="value" name="products[<?php the_id(); ?>]" />
How can I marry up the product to the order quantity and then send that to the order form for processing, this part I can do myself.
Thanks In advance
You can name the product quantity based on it's ID like this:
<input type="text" name="item[<?php the_id(); ?>]" />
You can then access the product quantities on the server side using for each:
foreach($_POST as $index => $value){
// $index is product id and $value is product quantity
}
Why not put the quantity in a separate input field. In case of a normal text field the visitor can then even change the quantity:
<input type="text" id="item1" name="ordered-items[]" /><input type="text" id="qty1" name="quantity[]" />
<br>
<input type="text" id="item2" name="ordered-items[]" /><input type="text" id="qty2" name="quantity[]" />
<br>
<input type="text" id="item3" name="ordered-items[]" /><input type="text" id="qty3" name="quantity[]" />
In php you can process the data like this:
<?php
$items = $_POST['ordered-items'];
$quantities = $_POST['quantity'];
for($i = 0; $i < count($items); $i++) {
echo $items[$i] . ' has quantity ' . $quantities[$i];
}
Hi I'm quite new to php and I'm currently making a webpage similar to the ones used by supermarkets for stock management control as part of an assignment. I have the following form where the cashier would enter the product Id and the quantity of the item being purchased.
The form will then call another php file named cashsale.php which will take these inputs and update the tables in my database so that levels of stock on shelves in supermarkets are up to date with the new amounts (i.e. older qty - qty entered) and management can be advised when reorder is needed.
As it is the form works well, however I was advised to edit it in a way that a cashier can enter multiple products and quantities before submitting (i.e. the form will sort of show itself again) and allow the user to edit or remove any items before actually submitting the values to cashsale.php to manipulate the tables. I seem to be at a loss as to how this can be done.
I wanted to create a new button named "Add" which would display the form again, i.e. allow the user to check in more items, but I am confused as to how this can be done and also as to how I will be able to update tables then since I would be having more then just 2 inputs.
Can anyone help me on this please? Thanks in advance. The following is my html form:
center form action="cashsale.php" method ="post"
Product ID: <input name= "id" type="int" > <br>
Quantity:<input name="qty" type="int">
<input type="button" name = "Add" onclick="add">
<input type="Submit" name ="Submit" value = "Submit">
form center
I was not allowed to use html tags for form and center so I removed the < >. The following is some of the modifications done in the cashsale.php file just to give a clearer example.
$result = mysql_query("SELECT * FROM shelfingdetails where prodId =' " .$id. " '");
if (!$result){
die (mysql_error());
}
while ($row =mysql_fetch_array($result))
{
$qtyOnShelf= $row ['QtyOnShelf'];
$max=$row['max'];
$newQtyShelf=$qtyOnShelf-$qty;
}
$update=mysql_query("UPDATE shelfingdetails SET QtyOnShelf ='". $newQtyShelf. "' where prodId = '". $id. "';");
I hope someone can help. Thanks!
You just have to pass an array. For this you have to generate the inputs with PHP or javascript (I'm gona use jQuery to keep the code nice and simpe).
If you use PHP:
// PHP
<?php
if(isset($_POST['submit']) && $_POST['submit']){
//save data
} elseif(isset($_POST['Add']) && $_POST['Add']) {
$max = (int)$_POST['max']
} else { $max = 1; }
?>
<form action="" method="post">
<?php
for($i = 0;$i < $max;$i++){
?>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<?php
}
?>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="submit" name="Add" />
<input type="submit" name="Submit" value="Submit" />
</form>
If yo use Javascript:
//HTML
<form action="" method="post" id="form">
<div id="add">
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
</div>
<input type="hidden" name="max" value="<?= $i; ?>" />
<input type="button" name="Add" onclick="addRow();" />
<input type="submit" name="Submit" value="Submit" />
</form>
// jQuery
function addRow(){
$("#add").append("<br />Product ID: <input name='id[]' type='int' >" +
"<br />Quantity: <input name='qty[]' type='int'>");
}
you have to use id[] and qty[] to pass them as an array and with the add button generate as many of them as you need. Like so:
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int"> <br>
Product ID: <input name="id[]" type="int" > <br>
Quantity: <input name="qty[]" type="int">
<input type="button" name = "Add" onclick="add">
Then on the backand use for loop to save all the data.
$max = count($_POST['id']);
$id = $_POST['id'];
$newQtyShelf = $_POST['qty'];
for($i = 0;$i < $max;$i++){
$update=mysql_query("UPDATE shelfingdetails
SET QtyOnShelf ='". (int)$newQtyShelf[i]. "'
WHERE prodId = '". (int)$id[i]. "';");
}
I just wanted to show you the idea, please don't use this specific code, because you should use mysqli instead of mysql and also mysqli_escape_string to make sure that the user not submits incorrect data.
How to increase/delete quantity of a product in PHP MySQL or javascript? Or how to insert a quantity value of a product along with a checkbox?
<form action="addtocart.php" method="post">
<table width="100%" cellspacing="20px">
<?php
include 'dbconnect.php';//for connection
$sql='select * from product';
$res = $dbconn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$res->execute();
$disp="<tr><th>Image</th><th>Product Name</th><th>Price</th><th>Add To Cart</th></tr>";
while($rs=$res->fetch())
{
if($rs['availableOnline']==1)
$isonline="Yes";
else
$isonline="No";
if($rs['availableInStore']==1)
$isstore="Yes";
else
$isstore="No";
$disp.="<tr>";
$disp.="<td><img src=".$rs['imageLink']." width=50 height=70></img></td>";
$disp.="<td>".$rs['name']."</td>";
$disp.="<td>$ ".$rs['price']."</td>";
$disp.="<td><input type=checkbox value=".$rs['idProduct']." name=items[] > Add Item</td></tr>";
$disp.="<tr><td> </td><td>Available Online : ".$isonline."</td><td>Available in Store :".$isstore."</td><td> </td></tr>";
}
echo $disp;
?>
<tr><td> </td><td><input type="submit" id="btnsubmit" value="Add To Cart" /></td></tr>
</table>
</form>
Let me show you with an example, for dynamic quantity change , we can use javascript
index.php
<a herf="#" onclick="increase()"> Increse</a>
<input type="number" min=0 max=100 id="quantity" name="quantity" value="1">
<a herf="#" onclick="decrease()"> Decrease</a>
<input type="checkbox" name="fruit[]" value="1">Orange<br>
<input type="checkbox" name="fruit[]" value="2">Banna<br>
<input type="checkbox" name="fruit[]" value="3">Kiwi<br>
javscript
We will used the 'id' to get the value of a number(input)
function increase()
{
e=parseFloat(document.getElementById("quantity").value);
e+=1;
document.getElementById('quantity').value=e;
}
function decrease(){
e=document.getElementById("quantity").value;
e-=1;
//to prevent from quantity going less than zero
if(e>0)
{
document.getElementById('quantity').value=e;
}
}
save.php
in second php we will use implode function to store multiple value
$quantity= $_POST['quantity'];
$fruit= implode(',' , $_POST['fruits']);
echo $fruit; //used that value to store in database result will be like this 1,2,5,6
I have a problem to combine the checkbox and textbox values. Here my snipet code :
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
<input type="checkbox" name="id_staf[]" value="query from database">
<input type="text" name="note[]" value="any text entered">
<br>
this is my php code to process that form:
$array_id_staf = $_POST['id_staf'];
$array_note= $_POST['note'];
for($a = 0; $a < count($array_id_staf); ++$a) {
echo $query1 = "UPDATE peserta SET note='$array_note[$a]' WHERE id= '$array_id_staf[$a]'<br>debugging";
//----------------------testing---------------------------#mysql_query($query1); // hold first for debugging
} // Closing for
if all checkbox were checked, the result os going fine. But if the second and 3rd were checked, array $array_note become wrong.
Please help me. Thanks in advance.