foreach loop through specific $request - php

I have a form that has several input types all that need to be a handled differently. I did a loop to name them like so in the form:
product-0-length
product-0-size
product-1-length
product-1-size
product-2-length
product-2-size
On my processing php (where the form info gets sent) I want to iterate a loop to handle say size different from length. My thought was this but no luck:
<?php
$i = 0;
foreach($_REQUEST['product-'.$i.'-length'] as $key => $val) {
//style or do what I need with the length information for each product
echo '<li>'.$key.'='.$val .'</li>';
$i++;
}
?>

As I suggested in the comments above you could use a different naming scheme for your input fields. Take a look at this example for the form creation:
<?php
foreach ($i=0; $i<3; $i++) {
echo "<input type=\"text\" name=\"product[$i][length]\">\n";
echo "<input type=\"text\" name=\"product[$i][size]\">\n";
}
When submitting this form the server will translate the notation into a php array which is a very convenient thing. You can simply iterate over that array:
<?php
foreach ($_POST['product'] as $key=>$product) {
echo "<li>Length of product $key: " . $product['length'] . "</li>\n";
echo "<li>Size of product $key: " . $product['size'] . "</li>\n";
}
Note that this is a very primitive example, all error checking and the like is missing to keep things crunch. Also I did not test this code here, it is just meant to point you into the right direction, but I hope there are not too many typos in there...

Related

form post of values in array and manage them divided by key

I dont know how to manage this situation, I'm a noob coder, I have a page that shows you all available lots where you can unload a specific item from that lot.
This is the foreach that prints out:
$lotto, $totalelotto, $data, and ask for qtyvalue to unload from $lotto (input can be also NULL)
foreach ($dataslotto as $data) {
$totalelotto = totlotto($database, $data['lotto']);
$lotto = $data["lotto"];
$data = $data["data"];
echo "<tr>";
echo "<td>".$lotto."</td>";
echo "<input type=\"hidden\" value=\"".$lotto."\" name=\"array[]\" />";
echo "<td>".$totalelotto."</td>";
echo "<input type=\"hidden\" value=\"".$totalelotto."\" name=\"array[]\" />";
echo "<td>".$data."</td>";
echo "<input type=\"hidden\" value=\"".$data."\" name=\"array[]\" />";
echo "<td><input type=\"text\" class=\"form-control\" placeholder=\"Qta.\" required name=\"qtyvalue\"></td>";
echo "</tr>";
}
I dont know how to set name="" of input fields (because the number of fields can change if there are many lots) and I dont know how to send $_POST data as array, and then foreach group of $lotto, $totalelotto, $data, $qtyvalue where is set $qtyvalue do another query.
I put it in no regular code, I know it looks bad but it's just for giving you an idea.
$_POST[''formarray];
foreach ( /* values recieved in each <tr> inside formarray where $_POST['qtyvalue'] is not empty */ ){
#EXECUTE THIS
}
Thanks for help!!
And sorry for my bad coding skills.
$_POST is an Associative/Key Value pair, it's key is whatever is set as the inputs name.
so if you wanted to send the users input username to the backend PHP script
You set the value and it's name
<input type="text" name="username" value="User123">
then to retrieve the user name you can do
print_r($_POST["username"]);
to print the value.
So you ask how do you loop over each one in $_POST, that's pretty simple you can could a foreach loop over the entire $_POST array.
foreach($_POST as $key => $value)
{
//check something has been entered for the current value we are iterating over
if($value != null)
{
print_r($key . " value is : " . $value);
}
}
this would loop over each item in the $_POST array with key being set to whatever the DOM elements name is.
Don't forget the $_POST array is just that an array, you could do
var_dump($_POST);
and see everything that was sent in the POST request.
You can use array names for your inputs. Say you have a row of your table like this:
<tr>
<td><input ... name="lotto[]"></td>
<td><input ... name="totalelotto[]"></td>
<td><input ... name="data[]"></td>
<td><input ... name="qtyvalue[]"></td>
</tr>
Then you will get arrays $_POST['lotto'], $_POST['totalelotto'] and so on, each with the same number of elements, and elements with same index belonging to one row of the table. You could then process those elements like this
foreach ($_POST['lotto'] as $i=>$lotto) {
if ($_POST['qtyvalue'][$i] > 0) {
...
}
}

Calling in indexes in session variables

I have been trying to do this for a few days, and I cant seem to find anything on the net about it, but then again I am not really sure what I should be searching, plus it may not even be possible.
So I have a form which is looped dependent on how many parcels they wish to send, I loop the names using the index in the loop, as you can see below. so it goes like 'Weight . $i' = 'Weight1' and so on...
I then stores these into session variables, but now I want to pull through all the session variables for those that are set, and I wanted to be able to loop through the session variables as I am trying to display like a summary page of all the parcel details, as shown in below code?
I have sessions called PWE1, PWE2 etc and want it to loop through them rather than calling them individually.
Is this possible? if so how?
<h4>Parcel Details</h4>
<?php
if($SV != null){
$i = 0;
do {
$i++;
?>
<h3>Parcel <?php echo $i;?> </h3>
<p> Weight: <?php echo $_SESSION['PWE' . echo $i ]; ?> </p>
<?php
} while ($i != $SV);
}
?>
Why not use a 2d array and loop through it?
// store your PWE1, PWE2 etc in here
$_SESSION["weights"]["PWE1"] = $value;
$_SESSION["weights"]["PWE2"] = $value2;
$_SESSION["weights"]["PWE3"] = $value3;
$i = 0;
foreach($_SESSION["weights"] as $pwe) {
echo '<h3>Parcel' . $i . '</h3>';
echo '<p>Weight:' . $pwe . '</p>';
$i++;
};

Store checkbox group values as a variable

I am trying to store the values of selected checkboxes on a multi page form so I can include these on the final page of the form (and in the email that is sent to the site owner).
I have worked out how to display the values, but saving them for later has got me stumped. I'm learning as I go so I wouldn't be surprised if this is quite easy...
This is the code I'm using:
<?php foreach ($_POST['fooby'] as $key => $entry) {
if(is_array($entry)){
print $key . ": " . implode(',',$entry) . "<br>";
}
else {
print $key . ": " . $entry . "<br>";
}
} ?>
And this is the result I get:
1: Minor Service £129
2: plus MOT £35
That's exactly what I'm after - though I don't need the numbers at the beginning. How do I save that information for later?
With the updated code below, I now get the following result:
Minor Service £129
plus MOT £35
That's perfect, but I'm struggling to work out how to store that information to a session variable. I should point out that the values returned from the form are dynamic and unknown beforehand. There might also be 10 items in the array, not just the two shown above.
What I have so far:
<?php if (isset($_POST['fooby'])){
foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
$dokval = implode(',',$entry) . "<br>";
echo $dokval; //echoes the expected result on the page
$_SESSION['dokvalues'] = $dokval; //only stores the last item
}
else {
print $entry . "<br>"; //not rewritten this part yet
}
}
} ?>
Simply insert these values in hidden input elements in a form on the following pages to use them again:
<input type="hidden" name="<?php echo $key1; ?>" value="<?php echo $value1; ?>" />
<input type="hidden" name="<?php echo $key2; ?>" value="<?php echo $value2; ?>" />
...
The foreach loop iterates through the array and for each iteration $key variable is the current index and $entry is the value of that index. The numbers in the list are just representation of index values. If you don't need them, you can go for this:
<?php foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
print implode(',',$entry) . "<br>";
}
else {
print $entry . "<br>";
}
} ?>
The keys will still stay in $_POST['fooby'] array.
The variable $entry holds one value of the array each time the foreach loop iterates. So the variable $dokval will also hold only one value, which it echos each time the loop iterates. By the time you look at the session variable it's value is going to be the last value that $dokval held. Make $dokval an array and push the $entry value into it. array_push. Also, make sure you start a session at the beginning of every page you want to use the $_SESSION variable.
Jeff

Different elements with the same name in PHP

In PHP, I would like to know how to provide the same name to different elements and still echo them out individually. I think the array mechanism works here but I don’t know how.
echo "<input type='checkbox' name='seat[]' id='something'/>";
echo "<input type='checkbox' name='seat[]' id='something1'/>"
Then to echo their values out I use the following:
<?php
if(isset($_POST['seat[]']))
{
echo ' ', $_POST['seat[]'] ;
}
?>
Please guide me!!
It's just an array of data. You can access elements of it just like any other array:
foreach ($_POST['seat'] as $seat) {
echo $seat . "<br>\n";
}
or using a numerical index:
echo $_POST['seat'][0]; // value of the first submitted checkbox

create a single form using multiple inputs through xml file

here is my problem. I have an xml file that acts like a small database. My php code goes through the xml file and retrieves the info creating a form. For example, the xml file holds info about a menu, the user chooses salad, then the code will print out all types of salads and the user then chooses his favourite salad. The actual problem is that there are different portions; small and large and different prices for each!
I am not able to keep track of the selected item... X(
Any help??
Thanks in advance
here is my code:
<?php
foreach ($xml-> CATEGORY as $category)
{
if($_GET['category']==$category["id"])
{
echo "<h3>".$category ["id"]."</h3>";
echo "<br />";
echo "<form method=\"post\" action=\"add.php\">";
foreach ($category -> FOOD as $food) {
echo "<li>";
echo "<b>".$food["name"]."</b>";
echo "<hr>";
echo "</li>";
echo "<select name=\"variations[]\">";
foreach($food -> PRICE as $price)
{
echo "<option value=\"$price\">";
echo "<ul>";
echo $price["size"]. " ";
echo $price;
echo "</ul>";
echo "</option>";
}
echo "</select>";
echo "<input type=\"submit\" value=\"Buy this\">";
}
echo "<br />";
echo "<br />";
}
echo "</form>";
}
?>
the cart looks something like this
<?php
echo "<br>";
$values = $_POST['variations'];
foreach($values as $value)
{
echo $value;
echo "<br>";
}
?>
the code above only shows prices about small items. Large items are somehow ignored!! This code is not actually what I meant to do but it's an start. It should say:
You have chosen a large portion of greek salad for £10.50.
So, I should be able to pass three variables that I don't know how: $price[size], food and $price...
Thanks for your time
if i understand you correctly, you are just recieving the selected size (price) but not the actual meal?
well two possible solutions:
version one:
create a second form field that holds the selected meal.
i think its elegant and logical if you have checkboxes for the meals and then radio buttons or lists for the size... so you can check/uncheck meals but if its check you need to select a size...
you can also just let the user select the price and dynamlically select the the meal field too with javascript but i wouldnt suggest that, if you want this kind of user experience, i'd opt for vesion two
version two:
include the meal in the value of the input field that for the price. maby seperated by a comma or as a json encoded string.
then when you retrieve the post variable you can split/decode...
if you give me a working example which i can just paste into a file and hit it (including the xml object) i can quickly do that for you...

Categories