How to fetch dynamically generated input field's value in php? - php

I'm working on a form where I have 2 fields which can be added N number of times. I have 2 fields called "fieldA" and "fieldB" and a button called "addrow" . So as many times I click on addrow I add fieldA and fieldB beneath previous fieldA and fieldB. So I can have unlimited fieldAs and unlimited fieldBs. I use jquery to add rows and append new fields with number behind each field's name attr to make it unique. So first set of fields will be named as fieldA1, fieldB1 and second set will be named as fieldA2 , fieldB2 and so on.
This is how my part of my form looks
And here's my jquery
$(document).ready(function(){
var $i = 1;
$('body').on('click','#addrow',function(){
$('#fieldset').append(
"Your Friends Name: <br /><input type='text' name='fieldA"+$i+"' /><br /><br />Your Friends Email: <br /><input type='text' name='fieldB"+$i+"' /><br /><br />"
);
$i++;
});
});
Now since these fields are generated automatically using jquery I'm not sure how to fetch field's value in php.
also after fetching field's values I would also like to create an array.
This is how I expect to save values of all my fields in php array.
$fieldset = array(
array("fieldA" => "value of fieldA1","fieldB" => "value of fieldB1"),
array("fieldA" => "value of fieldA2","fieldB" => "value of fieldB2"),
array("fieldA" => "value of fieldA3","fieldB" => "value of fieldB3"),
...
);

You inputs must be array [], otherwise you will not be able to receive them as array fieldA[]
Your jQuery should be like this:
$(document).ready(function(){
var $i = 1;
$('body').on('click','#addrow',function(){
$('#fieldset').append(
"Your Friends Name: <br /><input type='text' name='fieldA["+$i+"]' /><br /><br />Your Friends Email: <br /><input type='text' name='fieldB["+$i+"]' /><br /><br />"
);
$i++;
});
});
HTML
Your Friends Name: <br /><input type='text' name='fieldA[0]' class='name'/><br /><br />
Your Friends Email: <br /><input type='text' name='fieldB[0]' class='email'/><br /><br />
and in your PHP you will receive them as
[fieldA] => Array (
[0] =>
[1] =>
[2] =>
)
[fieldB] => Array (
[0] =>
[1] =>
[2] =>
)
you can convert them as you want
$newArray = array();
for($i=0; $i<count($_POST['fieldA']); $i++){
$newArray[$i]['fieldA'] = $_POST['fieldA'][$i];
$newArray[$i]['fieldB'] = $_POST['fieldB'][$i];
}

if you're using POST to submit those fields in your form, you can do:
foreach ($_POST as $key => $value) {
$fieldset[$key] => $value;
}

Related

Show only the specific indexed array

How can I show only the specific index? For example, here's my UI.
As you can see in the picture I have 3 checkboxes and 3 textboxes with array value.
Let's say these are the name of the element.
<input type="checkbox" name="check[]">
<input type="text" name="textbox[]">
Then print the array:
$check = $_POST['check'];
$total_rec = $_POST['textbox'];
echo 'Check Array<br>';
print_r($check);
echo '<br<br><br><br>';
echo 'TextBox Array<br>';
print_r($textbox);
Result:
Check Array
Array ( [0] => 2 )
TextBox Array
Array ( [0] => [1] => 2 [2] => )
As you can see in textbox array all index showed, all I want is to show only the specific index with value and that is the 1 => 2 only.
use empty(), return true if contain value, example :
//iterate each $total_rec's member
foreach($total_rec as each){
//if $each not empty, do something
if(!empty($each)){
echo $each;
}
}
You are using $total_rec for post values of both checkbox and text. You can filter the array of text input like this:
$total_rec_text = $_POST['textbox'];
$total_rec_text = array_filter($total_rec_text, function($arr){
return !empty($arr) ? true : false;
});
You need to loop over $_POST array and check if checkbox is checked.
If checked, then only, get/print value.
Also, in HTML, you need to add specific counters to both checboxes and
textboxes.
As only checked checboxes get posted and texboxes get posted by
default.
<input type="checkbox" name="check[0]">
<input type="text" name="textbox[0]">
<input type="checkbox" name="check[1]">
<input type="text" name="textbox[1]">
<input type="checkbox" name="check[2]">
<input type="text" name="textbox[2]">
if (isset($_POST['check'])) {
foreach ($_POST['check'] as $idx => $value) {
echo "<br/>" . $_POST['check'][$idx] . ' ' . $_POST['textbox'][$idx];
}
}

How to insert array data to mysql table

I have two tables called op_group and options .These two tables are filled by array values. For example, I want to insert pizza details into my tables.
It look like this:
Cheese pizza and Sausage pizza will get inserted into the op_group table.
Other data will get inserted into the options table. These options should be inserted based on the relevant foreign key op_group id.
This is what i have tried. All details are inserted but not for the relevant op_group.
$opg_name=$_POST['opg_name'];
$price=$_POST['price'];
$itemCountz = count($opg_name);
$itemValues=0;
$queryValue1 = "";
for($i=0; $i<$itemCountz; $i++) {
$itemValues++;
if($queryValue1!="") {
$queryValue1 .= ",";
}
$queryValue1 = "INSERT INTO op_group
(opg_id,ml_id,cat_id,res_id,res_name,op_grp)
VALUES(NULL,'".$ml_id."','".$cat_id."','".$res_id."','".$res_name."','".$_POST["opg_name"][$i]."')";
$result1= mysql_query($queryValue1)or die(mysql_error());
$query6= "SELECT * FROM op_group ORDER BY opg_id DESC LIMIT 1" ;
$result6= mysql_query($query6);
while($row6 = mysql_fetch_assoc($result6)){
$opg_id=$row6['opg_id'];
}
$itemCount2 = count($price);
$itemValues1 = 0;
$queryValue2 = "";
for($j=0;$j<$itemCount2;$j++) {
if(!empty($_POST["op_name"][$j])||!empty($_POST["price"][$j])) {
$itemValues1++;
if($queryValue2!="") {
$queryValue2 .= ",";
}
$queryValue2 = "INSERT INTO options (op_id,opg_id,ml_id,cat_id,res_id,res_name,opt,price) VALUES (NULL,'".$opg_id."','".$ml_id."','".$cat_id."','".$res_id."','".$res_name."','".$_POST["op_name"][$j]."','".$_POST["price"][$j]."')";
}
}
$result2=mysql_query($queryValue2)or die(mysql_error());
}
This code give result like this
options table inserted data looks like this
how to solve this?
The reason why you are seeing options being duplicated for each option group is because your $queryValue2 is being repeatedly executed for each option group inside your outer most for($i = 0; $i < $itemCountz; $i++) loop.
As it stands, your current way of organizing the $_POST inputs are quite messy (and so are your duplicated row attributes). I will suggest you group your HTML inputs fields by each option group. You can try something like this:
<div>
<input type="text" id="first_order" name="orders[0][name]" /><br />
<input type="text" name="orders[0][options][0][price]" /><br />
<input type="text" name="orders[0][options][0][size]" /><br />
<input type="text" name="orders[0][options][1][price]" /><br />
<input type="text" name="orders[0][options][1][size]" /><br />
</div>
<div>
<input type="text" id="second_order" name="orders[1][name]" /><br />
<input type="text" name="orders[1][options][0][price]" /><br />
<input type="text" name="orders[1][options][0][size]" /><br />
<input type="text" name="orders[1][options][1][price]" /><br />
<input type="text" name="orders[1][options][1][size]" /><br />
</div>
Notice how I use the HTML name attribute to group the food options by the food. Then if you submit this form, you will see that the $_POST array appears to look something like this:
Array
(
[orders] => Array
(
[0] => Array
(
[name] => "Cheese Pizza"
[options] => [0] => Array([size] => "8'"
[price] => "12")
[1] => Array([size] => "12'"
[price] => "14")
)
[1] => Array
(
[name] => "Sausage Pizza"
[options] => [0] => Array([size] => "8'"
[price] => "13")
[1] => Array([size] => "12'"
[price] => "16")
)
)
)
Now you can tidy up your backend PHP codes with something like this:
foreach ($_POST['orders'] as $orders) {
// .. some codes
foreach($orders as $order) {
// .. add codes to insert into op_groups where $order['name'] will give you the pizza name
foreach($order['options'] as $details) {
// .. add codes to insert into options where $details['size'] and $details['price'] will give you the corresponding values
}
}
}
Also, you can use mysqli.insert-id to get the row ID of the last inserted row. Then you can get rid of that silly $query6 and its while loop.
Of course, don't forget to sanitize your $_POST inputs before using them!
I am getting a bit tired, if there are mistakes, I will fix them up tomorrow. Hope it helps!

How can I combine values of checkboxes with values of text in php?

I'm new with PHP, and I'm making a html form which consist basically in two options: First, the client select a series of checkboxes (parts from an equipment) and then write the amounts of each selected checkbox...
<td><input id="11.11.015.0002" name="pecas[]" type="checkbox" value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[]" size="7" type="text" /></td>
and in php:
if(isset($pecas))
{
$mensagem .= "Peças Selecionadas:<br /><br />";
}
else {
echo "<script>alert('Selecione as Peças Desejadas!'); location.href='http://www.lyuz.com.br/pecas/erro';</script>";
exit;
}
foreach ($pecas as $pecas_s) {
} $mensagem .= " - ".$pecas_s."<br />";
That gave me all the selected checkboxes (parts), now I'm trying to get only the input_text (amounts) associate with these selected checkboxes..
I'm stuck. Help.
Specify a key in the name of each element. Use a number and just make sure that pecas[1] corresponds to qntd[1]. Then when you loop over one of the arrays, the keys will be the same in the other array. For example:
<?php
$count = 0;
foreach($itemList as $item){
echo "<tr>\n";
echo " <td><input type='checkbox' id='{$item['id']}' name='pecas[{$count}]'></td>\n";
echo " <td><input type='test' id='{$item['id']}' name='qntd[{$count}]'></td>\n";
echo "</tr>\n";
$count++;
}
If there are 3 checkboxes and quantity boxes, and lets say the 1st and 3rd boxes are checked, but not the 2nd. Your post array will look like:
array(
'pecas'=> array(
0 => 'some value', //notice, no 1 key because the second checkbox was not checked.
2 => 'some other value'
),
'qntd' => array(
0 => 'some qntd',
1 => '' //1 was not checked, so nothing should have been entered in the second textbox.
2 => 'some other qntd'
)
);
The keys 0 (first checkbox) and 2 (third) will exist in the 'pecas' array and will correspond with keys 0 and 2 in the 'qntd' array. You can then loop over the data like:
//check that at least one checkbox was checked
if(!empty($_POST['pecas'])){
//loop over the checkboxes getting key ($k) and value ($v).
foreach($_POST['pecas'] as $k=>$v){
//display a message
echo "Pecas {$v} ({$k}) was checked with a qntd of {$_POST['qntd'][$k]}<br>";
}
}
Change
foreach ($pecas as $pecas_s) {
$mensagem .= " - ".$pecas_s."<br />";
}
to
for($x = 0; $x < count($pecas); ++$x) {
$mensagem .= " - ".$pecas[$x]. ": " . $qntd[$x] . "<br />"; //Example
}
Since it appears that for every $pecas there is a $qntd, so you just need to get the index location of $pecas, and grab that same index location in $qntd
--
Let me add however that checkboxes only get passed IF they are checked, the input boxes will ALWAYS be passed. So you could have a disparity, where the indexes don't align! You might want to use some javascript to disable an input box if its checkbox is not selected.
Well, I manage to solve this with help of #Jonathan Kuhn with a little different approach.
In HTML form, I gave indexes in each element,
<td><input id="11.11.015.0002" name="pecas[1]" type="checkbox" value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[1]" size="7" type="text" /></td>
And in PHP file, I replace
foreach ($pecas as $pecas_s) {
$mensagem .= " - ".$pecas_s."<br />";
}
to
array('pecas'=> array(), 'qntd' => array());
if(!empty($_POST['pecas']))
{
foreach($_POST['pecas'] as $k=>$v)
{
$mensagem .= "- {$v} - QUANT.: {$_POST['qntd'][$k]}<br>";
}
}
And, finally, my mail returns value of each textbox when the checkbox is checked! \o/

PHP input array question

I have a form which includes 3 date of birth inputs like the following:
<label>Date of Birth</label>
<input type='text' size='2' maxlength='2' name='DOB[2]' />
<input type='text' size='2' maxlength='2' name='DOB[3]' />
<input type='text' size='4' maxlength='4' name='DOB[1]' />
The order of the inputs work as month/day/year. I am sending this to my script which then implodes the DOB array like such (Thanks to #Matt H.):
if(isset($_userData['DOB']))
$_userData['DOB'] = implode('-', $_userData['DOB']);
Now, the problem is, this implodes it to the improper format of month/day/year, which is not the order of the array I set, but the order of the inputs. Am I stuck with having to manually concatenate the array into the format I need for MySQL (year/month/day) ?
Sort the array first:
if(isset($_userData['DOB'])) {
ksort($_userData['DOB']);
$_userData['DOB'] = implode('-', $_userData['DOB']);
}
Try:
if(isset($_userData['DOB'])){
ksort($_userData['DOB']);
$_userData['DOB'] = implode('-', $_userData['DOB']);
}
This will sort the array $_userData['DOB'] by key. Based on your input elements, it is going to become:
$_userData['DOB'] = array(
1 => 'YYYY',
2 => 'MM',
3 => 'DD'
);

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