php looping out form match new value with id? - php

I'm looping out a form for every thing in the database write out it's position as and also its id.
foreach ($foo as $thing) {
$HTML = "
<input type='text' value='$thing->position' name='newPosition[]'/>
<input type='hidden' value='$thing->id[]' name='id'/>";
}
On submit i want to extract everyones id and new position so i can change it in the database.
How to i extract everyones position with their id??
somehow return $_POST['newPosition'] and loop it to changes everyones position value in the database (thats not a problem), my problem is how to match it with its id?

You can name the position fields with id -
<input type='text' value='$thing->position' name='newPosition[$thing->id]'/>
After posting the data -
foreach($posted_data['newPosition'] as $id => $position) {
echo $id.' - '.$position;
}

You could do it like this
foreach ($foo as $thing) {
$HTML = "
<input type='text' value='$thing->position' name='newPosition[" . $thing->id . "][]'/>
<input type='hidden' value='$thing->id[]' name='id'/>";
}
and then when you get the data you just get the key as well
like so
foreach($array as $key => $value){}
That way newPosition is tied with the ID :)

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) {
...
}
}

Send array from HTML forn with predefines values

Hello i try to send an array multiple times from html form and later access this value's but im recieving undefined index. Can you please explain me what am i doing wrong here ?
First i take all values of checked checkboxe's
<label>
<input type="checkbox" class="ck" name="event[]" id="event" value="<?php echo $row['name'];?>"><span>Wybierz</span>
</label>
Later on i process it and return values into hidden input fields
$event = $_POST['event'];
foreach ($event as $key) {
echo "<input type='text' class='form-control' name='event2[]' value='" . $key . "' />";
}
And lastly i want to send this data together with some other input fields data to thankyou.php but im getting undefined index on my event2
if (isset($_POST['submit2'])) {
if(count($_POST['name']) > 0) {
$event2 = $_POST['event2'];
print_r($event2);
}
exit;
}
Till step 3 everything works perfectly fine .
On each request, only the values that are in the current form are sent to the server. If you want to keep them through multiple requests, either you save them in the session or output them as hidden fields in your form.
change this line:
$event = $_POST['event'];
to this line:
$event = $_POST['event[]'];
Let me know if that worked! :)

Catching POST data in php with variable ID

I'm creating a form from a database and the input id's could be 1-9, 1,2,5,8, etc. IE with the way it is now, I cannot determine what the number will be unless I were to iterate from number 1 to the final number of menu items in the database... which I imagine is not optimal from a coding perspective.
I have two files. File1 will get list number of menu items from a database and create a list. The condensed version of my code is as follows, please keep in mind i have condensed a lot of useless stuff;
File1.php
$menuArray = openMenu(1);
$return = "<div id='menu'><form method='post' action='file2.php'><input type='submit' name='submit' value='Commit Order' /><table class='tableinfo'>";
$i=1;
foreach($menuArray as $recordNum => $record)
{
if ($record['available'] > 0)
{
$thisClass='available';
} else{
$thisClass='unavailable';
}
$return.="<tr class='$thisClass'>
<td>$record[itemid]</td>
<td><label for='$record[itemid]'>$record[name]</label></td>
<td><button type='button' id='itemid-$record[itemid]' class='subtract'>-</button><input class='itemadder' id='itemid-$record[itemid]' type='number' min='0' value='0' /><button id='itemid-$record[itemid]' class='addition' type='button'>+</button></td>
</tr>";
}
$return.="</table></form></div>";
return $return;
File2.php
I don't know how to code this :(
Is anyone able to shed some light on the best way to do this?
I just need a way to be able to see what id's have a value when posted.
I am using jQuery at the moment; would this be something best done using jquery?
Assuming I understand you correctly the best way to do this would be to have an array of inputs.
Code you should try to achieve for your HTML output would need to be something like this:
<input type="text" name="number[1]" value="" />
<input type="text" name="number[3]" value="" />
<input type="text" name="number[5]" value="" />
Now you know after your form submission in PHP:
foreach($_POST['number'] as $id => $value){
echo 'The value for ID #' . $id . ' is ' . $value;
}
The script File1.php rendering the inputs above does know about what has rendered out. So what, if it also puts a list of rendered form element names in to the session for later use in file2.php:
In the beginning:
$_SESSION['formids'] = array();
in the loop:
....
$_SESSION['formids'][] = "itemid-" . $record[itemid];
and in file2.php:
$sendItems = $_SESSION['formids'];
...
foreach ( $sendItems as $itemId )
{
$val = empty($_POST[$itemId]) ? null : $_POST[$itemId];
if ( isset($val) )
...

retrieving data from checkbox using php

i have send the value dynamically from check-box and when i tried to retrieve all the value dynamically using loop, it just goes on loading.
my code for sending value from check-box:
while ($row=mysql_fetch_array($query))
{
$member_id=$row["member_id"];
<input type='checkbox' name='check' value='$member_id'>
}
// this is working. but when i try to fetch the data from checkbox from only where the tick is given it doesn't work. this is how i tried to fetch the data
while(isset($_POST['check']))
{
echo $_POST['check']."<br>";
}
The trick here is, when you have multiple checkboxes with the same name and you want to get all the checked values on the server side, then you need to add [] after the name of the checkbox field in the html, eg.
<input type='checkbox' name='check[]' value='$member_id'>
if you do this, then $_POST['check'] will be an array of all the checked elements. As pointed out by others,
while(isset($_POST['check']))
represents an infinite loop. It should be
if(isset($_POST['check']))
foreach($_POST['check'] as $each_check)
echo $each_check;
And finally, its a duplicate of an existing question. Please search before asking again :)
You added While loop, with the condition that will always true. So loop will become infinite.
Change you loop to foreach, like this
foreach ($_POST['check'] as $value)
{
echo $value."<br>";
}
AND your check-boxes will not show till then you add echo, like this
while ($row=mysql_fetch_array($query))
{
$member_id=$row["member_id"];
echo "<input type='checkbox' name='check' value='$member_id'>";
}
if you want to get all the checkboxes
WRONG WILL CAUSE INFINITE LOOP
while(isset($_POST['check']))
{
echo $_POST['check']."<br>";
}
One of the many correct alternatives:
foreach ($_POST['check'] as $val) {
echo $val.'<br>';
}
foreach ($_POST['check'] as $selected) {
$selections[] = $selected;
}
print_r($selections);
and change your html tag as :
<input type="checkbox" name="check[]" value=".$member_id.">

How to POST data as an indexed array of arrays (without specifying indexes)

i'm having some problem with posting data as an array of array. This is how i'd like my data to be POSTED:
array(
['someName'] =>
array([0] =>
array(['description'] =>890
['valore'] =>444)
[1] =>
array(['description'] =>98090
['value'] =>77)
)
I know i can achieve this if my html is like this:
<input type='text' name="someName[0][value]">
<input type='text' name="someName[0][description]">
<input type='text' name="someName[1][value]">
<input type='text' name="someName[1][description]">
My problem is that the input fields are on rows of a table and the user can add/remove as many rows as he want, so i can't have fixed index (or i have to modify the name of the input fields each time a row is added since every time i add a row i clone the upper row in the table)
So what i am asking is one of these two things:
1) is there a way to post data the way i want without specifing an index
2)if not, how can i modify dynamically the new input field so that they have an updated name with the new index?
EDIT - i had alredy tried using name="someName[value][]" and name="someName[description][]" but the output is not the desired one:
array(['terreniOneri'] =>
array(['descrizione'] =>array([0] =>890
[1] => 98090)
['valore'] =>array([0] =>444
[1] =>677)
)
i know i can iterate on this array in php i was just wondering if i could avoid it.
Do it the way you put in the question. If the user removes some row, your form elements would be:
<form action="..." method="post" onsubmit="return reindexer(this);">
<input type='text' name="someName[0][value]">
<input type='text' name="someName[0][description]">
<input type='text' name="someName[2][value]">
<input type='text' name="someName[2][description]">
</form>
But there's no problem to traverse an array with non-contiguous numeric indexes in php: use a foreach loop.
<?php
if (count($_POST['somename']) > 0)
{
foreach ($_POST['somename'] as $row)
{
echo "Value: ".$row['value']."<br />\n";
echo "Description: ".$row['description']."<br />\n";
}
}
If you need to know the number of each row as a continous index (in the example provided, row 0 would still be 0, but row 2 should be 1 (as the user deleted one row), you can use a variable acting as a counter:
<?php
if (count($_POST['somename']) > 0)
{
$i = 0;
foreach ($_POST['somename'] as $row)
{
echo "Index $i<br />\n";
echo "Value: ".$row['value']."<br />\n";
echo "Description: ".$row['description']."<br />\n";
$i++;
}
}
I think this approach has more sense that the other solutions, as this way you would have an array of items, being each item a value and a description, instead of having two separate arrays of values and descriptions and having to get the values for your item from those two arrays instead of one.
edit: I've modified the first piece of code to include the <form> element. This would be the accompanying js function:
<script type="text/javascript">
function reindexer(frm)
{
var counter = 0;
var inputsPerRow = 2;
for (var idx = 0; idx < frm.elements.length; idx++)
{
elm.name = elm.name.replace('%%INDEX%%', counter);
if (idx % inputsPerRow == 1)
{
// only increment the counter (or row number) after you've processed all the
// inputs from each row
counter++;
}
}
}
</script>
Try like this:
<input type='text' name="someNameValue[]">
<input type='text' name="someNameDescription[]">
If the fields are paired, they can be attached by the indexes. So if you have the 10th row, someNameValue[9] and someNameDescription[9] will be a pair. You can merge them.
EDIT:
You don't have to write the indexes manually, they will be automatically generated.
<input type='text' name="someName[]">
<input type='text' name="someName[]">
<input type='text' name="someName[]">
and
<input type='text' name="someName[0]">
<input type='text' name="someName[1]">
<input type='text' name="someName[2]">
will give the same result in your post array.

Categories