PHP How to GET the Form variables on multiple items? - php

I need to collect the form elements of a cart. The items are in multiples. I wish to collect them as a session or easy to use Array - I think the Array would be best?
How can I collect this information in process.php?
I hope I have made it clear.
The code is like this for each item:
<div class="product" id="pId_'.$id.'">
<input type="hidden" name="productID" value="'.$id.'" />
<input type="hidden" name="productURL" value="'.$url.'" />
<input type="hidden" name="productQty" value="'.$qty.'" />
<input type="hidden" name="productPrice" value="'.$price.'" />
</div>
So the use cart could have :
<div class="product" id="pId_2">
<input type="hidden" name="productID" value="2" />
<input type="hidden" name="productURL" value="site.com" />
<input type="hidden" name="productQty" value="1" />
<input type="hidden" name="productPrice" value="750" />
</div>
<div class="product" id="pId_45">
<input type="hidden" name="productID" value="45" />
<input type="hidden" name="productURL" value="example.co.uk" />
<input type="hidden" name="productQty" value="2" />
<input type="hidden" name="productPrice" value="100" />
</div>
These details are submitted to the form.. but how can I collect when productID is called twice or more?

If you just need to collect the items for processing later, another way of doing it is to loop through all the POST variables. PHP will collect all information submitted into a reserved variable, $_POST.
From there you could use a foreach to loop through the information collected as follows;
foreach ($_POST as $key => $value)
{
echo "$key = $value";
}
Where $key would be your someitem_ and $value would contain the actual value submitted.
This would work easier provided you did not have any other inputs in your form other then those of the shopping cart items, if not you'll have to do some logic to determine which were the records that were associated with your cart items.
On a side note, if it is possible to combine the 3 related input values into just 1, with the values separated by a character you defined (maybe something like <item>|<name>|<url>), it might make your life easier when trying to get all the 3 values that are associated with the id.
In that case your code would just get the string value for the specific id and do a split() on the '|' to break it up back into its 3 values.

If you add square-brackets to your input names
<input type="hidden" name="productID[]" value="' . $id . '" />
<input type="hidden" name="productURL[]" value="' . $url . '" />
<input type="hidden" name="productQty[]" value="' . $qty . '" />
<input type="hidden" name="productPrice[]" value="' . $price . '" />
you can then collect and use all form data by adding the following PHP code to your process.php file
foreach ($_POST['productID'] as $key => $getid) {
$getqty = $_POST['productQty'][$key];
$getprice = $_POST['productPrice'][$key];
$geturl = $_POST['productURL'][$key];
// Example MySQL Query
mysql_query("INSERT INTO orders (id, url, quantity, price) VALUES ('" . $getid . "', '" . $geturl . "', '" . $getqty . "', '" . $getprice . "')");
}
What this does is that it automatically creates arrays for the form data so that you can, using the PHP code above, collect the correct data from each row by using the index number via the $key variable.

I believe in your process.php form you could just store them in an array when you pull in the post data. You will need to pass the largest value of $id as a value as well so you can loop through the appropriate amount of items.
The top of your process.php might look like
<?php
$processArray = array();
$id = $_POST["id"];
$i = 0;
while ($i <= $id) {
$processArray = ('item' => $_POST["someitem"_.$i], 'name' => $_POST["somename"_.$i], 'url' => $_POST["someurl"_.$i]):
//Now you can do what you want with each value. Display it somewhere, store it somewhere, etc.
$i++;
}
I did this off the top of my head but that's what comes to mind when I look at your issues.

I'm not entirely sure of what you're asking. But you can retrieve arrays from $_POST if the field names are appended with [].
<input name="myArray[1]" value="foo" />
<input name="myArray[37]" value="bar" />
Would give you
array(
1 => 'foo',
37 => 'bar'
)

<form action="process.php" method="post">
These elements are looped pending on cart items
<input type="hidden" name="someitem['.$id.']" value="1" size="1" maxlength="1" />
<input type="hidden" name="somename['.$id.']" value="1" size="1" maxlength="1" />
<input type="hidden" name="someurl['.$id.']" value="1" size="1" maxlength="1" />
</form>

Use:
<input type="hidden" name="someitem[]" value="1" size="1" maxlength="1" />
And then in PHP $_GET["someitem"] will be an array
EDIT: Use $_POST["someitem"]. I had assumed you needed GET, because of the title of the question.

Related

Accessing "THIS" variable outside of string

I have adapted a shopping cart program which builds a series of items based on POSTED form data and combines that data to form the shopping cart. Each item is given a line in the cart using the $this command:
foreach($this->get_contents() as $item) {
echo tab(7) . "<input type='hidden' id='jcartItempartnumber-{$item['id']}'
name='jcartItempartnumber[]' value='{$item['partnumber']}' />
Part Number: {$item['partnumber']} \n";
}
So each line item accepts and removes the Part Numbers without issue. The issue becomes That I can't put these part numbers down in the footer of the cart itself with the subtotal.
echo tab(7) . "<span id='jcart-subtotal'>Cost: <strong>$currencySymbol" .
number_format($this->subtotal, $priceFormat['decimals'], $priceFormat['dec_point'],
$priceFormat['thousands_sep']) . "</strong></span>\n";
Is there an easy way to display the unique part numbers down below? How do I reference a $this variable outside of the $this string?
----EDIT----
Item 1 has several values.
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="2" />
<input type="hidden" name="my-item-name" value="Instrumentation Enclosure" />
<input type="hidden" name="my-item-price" value="0" />
<input type="hidden" name="my-item-partnumber" value="In" />
<input type="hidden" name="my-item-qty" value="1" size="3" />
For each cart option there is only a few values
for any item with an item ID of '2' there are only two possibilities; "R" and "In"
I just want to create a variable which echo's either R or In when the ID=2

PHP: Adding multiple products to post order form

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];
}

parsing dynamic POST variable

I have a form that may submit 1 line item or 200 to quote. using FPDF to create results and everything is working perfectly, but I was looking for a way to automate picking up post values. So far I have been doing them manually, which is very difficult to make code changes:
//conditional statement to verify values exist, otherwise we write a blank line
$item=$_POST['item3'];
$uprice=$_POST['uprice3'];
$udprice=$_POST['udprice3'];
$quan=$_POST['quan3'];
//add values to report
//repeat for next result
$item=$_POST['item4'];
$uprice=$_POST['uprice4'];
$udprice=$_POST['udprice4'];
$quan=$_POST['quan4'];
I was wondering if there is a way to add a variable inside the post value, like $_POST[$nextitem]?
You can loop until the next number is not available anymore:
<?php
$i = 1;
while (isset($_POST['item' . $i])) {
$item = $_POST['item' . $i];
$uprice = $_POST['uprice' . $i];
$udprice = $_POST['udprice' . $i];
$quan = $_POST['quan' . $i];
// do your stuff
$i++;
}
concatenating a string 'var' with int 1 will result in a string 'var1' in PHP.
I would just grab the entire array with $array = $_POST and then use foreach() loops to manipulate it later.
Alternatively, it sounds like you have an arbitrary number of things on your form. Do it like this:
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />
You can see more about this in this very helpful answer: HERE
When you submit this arbitrary number of fields, you will end up with a nice multi-dimensional array. Iterate over it like this:
$i = count($_POST['item']);
$payload = array();
while ($i <= count($_POST['item']) {
$payload[] = array(
'item' => $_POST['item'][$i],
'udprice' => $_POST['item'][$i],
'quan' => $_POST['quan'][$i]
);
$i++;
}
Now $payload is a fancy array that can be inserted into databases and such.

Keep printing same form until submit button is clicked

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.

Radio button post data of multiple input fields

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!

Categories