How to insert value of dynamically created input boxes into database [duplicate] - php

This question already exists:
how to post value of 3 input fields into database
Closed 9 years ago.
hello developers i am creating 2 text boxes and 1 select box dynamically using java script function... now i want to post the value of (n) fields created into database (relevant table)
as i am using codeigniter so m posting the script and code
this is the simple java script that i am using
<script>
var counter=1;
function generateRow() {
var count="<font color='red'>"+counter+"</font>";
var temp ="<p> <div class='_25'><input type='textbox' id='textbox' name='stop"+counter+"' placeholder='Stop Name'></input></div> <div class='_25'><input type='textbox' id='textbox' name='timing"+counter+"' placeholder='Timing'></input></div> <div class='_25'><select id='ampm"+counter+"' name='ampm"+counter+"'><option>a.m</option><option>p.m</option></select> </div>";
var newdiv = document.createElement('div');
newdiv.innerHTML = temp + count;
var yourDiv = document.getElementById('div');
yourDiv.appendChild(newdiv);
counter++;
}
</script>
and this is my division on php file
<div id="div">
</div>
<p> </p>
<div class="_25">
<p>
<input type="button" name="button" class="button red" id="button" value="Add" onclick="generateRow() "/></a>
</p>
</div>
<input type='button' value='Remove Button' id='removeButton'>
and this is my related table fields
route_number stop_name am_pm timing

My favorite way to do this is to use the DOM as much as possible. Don't use counters unless you absolutely have to (they're just a source of bugs). Here's a quick example:
Html/JS/jQuery (can vary, I crafted this to make it easy to follow):
<form method="POST" id="theForm">
<div id="fields">
<input type="text" name="fields[]"/>
</div>
<input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#addField').click(function() {
$('#fields').append(
$('<input type="text" name="fields[]"/>')
);
})
});
</script>
Note how I don't need to use any sort of counting variable. Just like PHP, you can create an array of POST variables without specifying indexes by using [] and the server (or browser? I'm not sure) will build the array for you. The order in which the <input /> fields are rendered on the page will be the order they are provided to your PHP via $_POST. This code...
foreach ($_POST['fields'] as $fieldIndex => $fieldValue) {
doStuff($fieldValue);
}
... will process each field in the order they were added. You can even use JavaScript to re-order or remove the inputs and that will be reflected in $_POST. This method, coupled with JSON encoding, makes for a fast and easy way to handle multi-input, free-form fields.
Update:
Applying the above code to your use-case requires a small addition that may not be obvious. You'll need to create an array for each of the three inputs (stop, timing, and ampm) like so:
<form method="POST" id="theForm">
<div id="fields">
<input type="text" name="fields[stop][]"/>
<input type="text" name="fields[timing][]"/>
<select name="fields[ampm][]">
<option value="am">AM</option>
<option value="pm">PM</option>
</select>
<br/>
</div>
<input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#addField').click(function() {
$('#fields').append(
$('<input type="text" name="fields[stop][]"/>'),
$('<input type="text" name="fields[timing][]"/>'),
$('<select name="fields[ampm][]"><option value="am">AM</option><option value="pm">PM</option></select>'),
$('<br/>')
);
})
});
</script>
Filling out this form with some test data yields the following array:
[fields] => Array
(
[stop] => Array
(
[0] => aaa
[1] => bbb
)
[timing] => Array
(
[0] => 1111
[1] => 2222
)
[ampm] => Array
(
[0] => am
[1] => pm
)
)
And to process that in PHP requires a simple old-school loop:
$numFields = count($_POST['fields']['stop']);
for ($i = 0; $i < $numFields; $i++) {
// Pack the field up in an array for ease-of-use.
$field = array(
'stop' => $_POST['fields']['stop'][$i],
'timing' => $_POST['fields']['timing'][$i],
'ampm' => $_POST['fields']['ampm'][$i]
);
saveToDatabase($field);
}
Unfortunately I don't have time right now to make sure all that is correct. It should be, and if its not it may still help :). I'll check back in a few hours.

name your dynamic input box "stop["+counter+"]" (using braces as part of the name) instead of adding a counter to the end of the name. Then in your post data, $_POST['stop'] will be an array of values that you can just foreach loop over with the counter as the key in the sub-array. And $_POST['stop'][1] will correspond to $_POST['timing'][1]...etc.

You can construct the following HTML input fields:
<input type="text" name="data[]" />
<input type="text" name="data[]" />
<input type="text" name="data[]" />
// ...
Which will lead to an array keyed data inside $_REQUEST super global, when you var_dump($_REQUEST['data']). Try it out. You don't even need to index the data[] array, since PHP will do it for you.
You might want to process your $_REQUEST['data'] or $_POST['data'] array with a foreach loop construct:
foreach($_REQUEST['data'] as $data){
// $data is the corresponding input field's value
}

Related

form checkbox group in php

im writing a code in php that need to take a data from html form.
i have few radio bottom and few checkbox bottom.
should i have for every bottom/label do varieble in php?
for example:this is from html
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" name="cats">חתולים<br/>
<input type="checkbox" name="dogs">כלבים<br/>
<input type="checkbox" name="hamsters">אוגרים<br/>
<input type="checkbox" name="goldfish">דגי זהב<br/>
<input type="checkbox" name="human">בני אדם
</td>
</tr>
for php:
if (isset($_POST["name"]))
{
$userName = $_POST["name"];
$userYearOfBirth = $_POST["yearOfBirth"];
$soulmate = $_POST["radio"];
}
It would be better to group the checkbox choices so you can access them as an array on the server in PHP. Additionally, move the name of the choice into the value of the checkbox. The new "name" will be whatever you want to call the checkbox group. I am using Animals for this example:
<form name="your-form-name" action="your-form-action-url" method="post">
<table>
<tr>
<td>חיות שאני אוהב/ת:</td>
<td><input type="checkbox" value="cats" name="animals[]">חתולים<br/>
<input type="checkbox" value="dogs" name="animals[]">כלבים<br/>
<input type="checkbox" value="hamsters" name="animals[]">אוגרים<br/>
<input type="checkbox" value="goldfish" name="animals[]">דגי זהב<br/>
<input type="checkbox" value="human" name="animals[]">בני אדם
</td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
On the server-side if users select more than one animal, all choices will be available in an array like this:
Array
(
[0] => cats
[1] => dogs
[2] => hamsters
[3] => goldfish
[4] => human
)
If they just select one, it'll still be an array:
Array
(
[0] => cats
)
Either way getting the results as an array lets you do something similar with the results whether they chose one or many choices from the list.
You can loop through all the choices and do whatever you need to with the data:
if (isset($_POST['animals'])) {
$animals = $_POST['animals'];
foreach ($animals as $key => $value) {
// do something with each $value .. maybe add to a database? echo back to user?
}
}
You actually don't need any new variables. You can use $_POST array as the variables.
Example (form side):
<form method="post">
<input type="text" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
echo $_POST['test']; // This will echo the input that named "test".
?>
The example above is valid for every method and input types.
In your case, your checkboxes will output "true" or "false" (Unless you define a value for the checkbox. If you define a value to it, it will output the defined value if the checkbox is checked.).
Example (form side):
<form method="post">
<input type="checkbox" name="test">
<input type="submit">
</form>
Example (PHP side):
<?php
if ($_POST['test'] === true)
echo "Yay! The checkbox was checked!";
else
echo "Oops! The checkbox wasn't checked!";
?>

What changes need to make to the HTML input fields in order to create desired array in PHP?

I've designed one HTML form as follows :
<form action="sample_test.php" method="post">
<input type="text" name="fileName" value="8.png" id="fileName[]">
<input type="text" name="fileLink" value="https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd" id="fileLink[]">
<input type="text" name="fileName" value="2_OnClick_OK.jpg" id="fileName[]">
<input type="text" name="fileLink" value="https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ" id="fileLink[]">
<input type="submit" name="Submit" value="Submit File">
</form>
Then the code in sample_test.php is as follows :
<?php
print_r($_POST); die;
?>
The output I got is as follows :
Array ( [fileName] => 2_OnClick_OK.jpg [fileLink] => https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ [Submit] => Submit File )
But this is not the desired output. I want the desired output array to be printed in following manner:
Array
(
[8.png] => Array
(
[0] => https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd
)
[2_OnClick_OK.jpg]
(
[0] => https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ
)
)
For now I've just demonstrated with two elements only but in real situations hundreds of such elements could present on the form.
So what changes do I need to make in my HTML as well as PHP code? Please help me.
Thanks in advance.
What you ask is impossible by just modifying the HTML code, because you would like a value (of fileName) to become an index in the array you get. That's impossible, the index will always be the name of the input.
However, if you have a look here : POSTing Form Fields with same Name Attribute , you will be able to get arrays of fileName and fileLink, and I'm pretty sure you can do something from there.
A few things wrong, but you are close. Make the name field an array instead of the id - plus your ids need to be unique.
<input type="text" name="fileName[]" value="8.png" id="fileName1">
<input type="text" name="fileLink[]" value="https://www.filepicker.io/api/file/zZ993JyCT9KafUtXAzYd" id="fileLink1">
<input type="text" name="fileName[]" value="2_OnClick_OK.jpg" id="fileName2">
<input type="text" name="fileLink[]" value="https://www.filepicker.io/api/file/1w3cKCW1TMmytb7md3XQ" id="fileLink2">
Not tested, but should do the trick.

How can I merge 2 input values from a form before performing a form action?

I am trying to create a form that gets a user directions to a pre-defined location from the location that they entered. I am using Bing Maps 'create a custom url map' to achieve this.
Based on msdn (http://msdn.microsoft.com/en-us/library/dn217138.aspx) I know I need the form to pass a single value such as the following: rtp=adr.'addressfromuser'~adr.'predefined address' . I just don't know how to merge the form values (or insert adr. in front of the user input). I have been unable to find a way to do this so any help is appreciated.
my code for my form is below:
<form action="http://bing.com/maps/default.aspx" method="get" target="_blank">
<label for="rtp">From:</label>
<input class ="input" type="text" name="rtp" value="adr." /> <!--user input-->
<input type="hidden" name="rtp" value="~adr.Mission,TX" />
<!--predetermined destination-->
<input class="btn btn-primary" type="submit" type="submit" value="Get directions" />
</form>
Ding this gets a result that is close to what I want but not quite there (would like to hide the initial "adr." and not generate a "rtp=" before the 2nd rtp being passed. Note: if I comment out the user inputs I successfully get a map with the final destination as point b, but no point a defined
If what I'm trying to do is possible help is appreciated!
You would need to array your ftp input:
EDIT: YOU NEED TO REMOVE adr. in the value="adr." on both rtp inputs!
<form action="http://bing.com/maps/default.aspx" method="get" target="_blank">
<label for="rtp">From:</label>
<input class ="input" type="text" name="rtp[]" value="" /> <!--user input-->
<input type="hidden" name="rtp[]" value="Mission,TX" />
<!--predetermined destination-->
<input class="btn btn-primary" type="submit" value="Get directions" />
</form>
Then, when you process the form, you would implode() that rtp[] array like so:
<?php
/* $_GET['rtp'] will look like this before implosion:
array(
0 => FromCity,UT
1 => ToCity,CA
)
*/
// You need to pre-append the adr. value to both strings by looping array
foreach($_GET['rtp'] as $value) {
$_rtp[] = "adr.'".$value."'";
}
/* Now $_rtp looks like this:
array(
0 => adr.'FromCity,UT'
1 => adr.'ToCity,UT'
)
*/
// Now implode this new array with "~"
// You could assign a new variable to the implode, but if you wanted to,
// you could override the same $_GET['rtp'] variable with it's imploded self.
$_GET['rtp'] = implode("~",$_rtp);
// Now the $_GET['ftp'] = adr.'FromCity,UT'~adr.'ToCity,UT'
?>
use javascript/jquery
$('form').submit(function(){
//do your actions here
$('input[name=rtp]').value()
return false; // prevents submit by default action.
});

Looping through multiple POST elements

I am trying to figure out how to loop through multiple POST form data that is dynamically pulled from a database and re-submit the modified data to a different table. For some reason (probably old age) I can't seem to come up with a solution that works.
I am already looping out all the records from one table (call it roster) and need to submit it to another table (call it roster2). The form is something similar to this:
<form name="name" action="form.php" method="post">
<input type="text" name="name1" value="15">
<input type="text" name="attended" value="1">
<input type="checkbox" name="nameid_12" value="12">
<input type="text" name="name2" value="8">
<input type="text" name="attended" value="1">
<input type="checkbox" name="nameid_6" value="6">
</form>
The 'name' and 'nameid' fields will always change and the number of records displayed will always be different (one day it could be 5 and the next 100).
What is the best way to loop through the POST data to submit it to the database keeping all the associations intact?
I am relatively new to working with PHP and I can't seem to figure out a good way to do this.
If you're going to generate them dynamically, I would recommend using PHP to place the ID of each form in the inputs on that form. So your original form would end up with these names:
<input type="text" name="name[12]" value="15">
<input type="text" name="attended[12]" value="1">
<input type="checkbox" name="nameid[12]" value="12">
<input type="text" name="name[6]" value="8">
<input type="text" name="attended[6]" value="1">
<input type="checkbox" name="nameid[6]" value="6">
Then your arrays will have keys corresponding to their form's ID. The array structure looks like this.
Array (
[name] => Array ( [12] => 15, [6] => 8 )
[attended] => Array ( [12] => 1, [6] => 1 )
[nameid] => Array ( [12] => 12 [6] => 6 )
)
Now we need to figure out which ids are actually present today. The array_keys() function generates an array of keys from any source array. Keys will be the same for each of the three elements, so I arbitrarily take the keys from [name].
$id_array = array_keys($_POST['name']);
Then, to access each element of the POST array, we'll use a foreach.
foreach ($id_array as $id) {
//assign variables
$name = $_POST['name'][$id];
$attended = $_POST['attended'][$id];
$nameid = $_POST['nameid'][$id];
//store
//Using whichever database style you like. I prefer PDO.
}
You can loop through the fields and retain their keys like so:
foreach ($_POST as $field_name => $field_value) {
// Storage
}

Passing multidimensional array data to PHP page taking values from dynamically created textboex

I need help regarding how to collect data from text boxes created dynamically. I am giving my html code. my adding and removing code for textboxes is working prefectly. I would like to know where i am doing wrong whether in defining array of textboexs. Whether i am not collecting textbox values properly. Another question is how should i pass this array value to another page after submitting page for inserting into DB.
This code is for taking values for itineraries for a tour for travel agent.
Here is my html form
`
Enter Itinerary Details
Name of Tour (category)
Days
City
Itinerary
Night Stay
-->
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<label></label>
<input type='text' id='dayNo' name="itinerary[]" >
<input type="text" id='cityName' name="itinerary[]">
<input type='text' id='schedule' name="itinerary[]">
<input type='text' id='nightStay' name="itinerary[]">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
<input type="submit" name="submit" id="submit" value="Submit" />
</td>
</tr>
</table>
</form>`
I would like to know does i have defined correct array name "itinerary[]".
If there are 10 days tour then there will be 10 rows containing 4 fields. How should i collect those rows and send to another page for inserting. Please let me how should i write the VALUES () section after collecting into array. Can i send this data of 10 rows using session. Can i send this data as parameter. I am sorry for so many questions in one post. I have tried all these way but no successes or most probably i m wrong somewhere
Please help me this is live site. Stuckedup in this part
Thanks millions in advance.
Sorry for this delayed reply to your ans. Actually i really getting no idea about how should i declear the arrays. Honestly this is mking me very frustrating. and loosing my time. Please Guide me if u can.
I am giving my JS code for adding the text box dynamically and in my previous post i have given the HTML code. Can u check please whether i am doing correct the naming convention for the declearing array. Please make necessary changes into my code please and paste here plz.
Here is my JS code adding textboxes dynamically
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>30){
alert("Only 30 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter + ' ' + 'style="width:750px;"');
newTextBoxDiv.html(
'<input type="text" name="itinerary[dayNo]'+ counter + '" id="dayNo'+ counter + '" value="'+ counter + '" >' +
'<input type="text" name="itinerary[cityName]'+ counter + '" id="cityName'+ counter + '" value="" >'+
'<input type="text" name="itinerary[schedule]'+ counter + '" id="schedule'+ counter + '" value="" >'+
'<input type="text" name="itinerary[nightStay]'+ counter + '" id="nightStay'+ counter + '" value="" >' );
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
No i am giving again my HTML code.. can you check whether i am giving the names properly or not.. It will be greatest help for me.
Here is my HTML Code
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label></label>
<input type='text' id='dayNo' name="itinerary[dayNo][]" >
<input type="text" id='cityName' name="itinerary[cityName][]">
<input type='text' id='schedule' name="itinerary[schedule][]">
<input type='text' id='nightStay' name="itinerary[nightStay][]">
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
<input type="submit" name="submit" id="submit" value="Submit" />
Now tell me how should i pass the values collected in the array to either session or thru URL like ---action="savedata.php?arr=...."
Please make correction in my code itself.. i m new and feeling very lost since last few days.
I wrote like this about passing the values to array
<?php
$totalArray = itinerary;
$_session['tArray'][]=$totalArray;
?>
Is this correct way to send thru session.
Thanks millions
in advance
I'm not sure to understand your issue very well, i'll try to explain steps.
Don't use generic ID for dynamics inputs.
PHP doesn't matter about id's
If you want to match a "block" of schedule, and match it with jQuery, set a proper data-* to each, or even a class.
Here's an example :
<div class="TextBox" data-formNum="0">
<input type='text' name="itinerary[dayNo][]">
<input type='text' name="itinerary[cityName][]">
<input type='text' name="itinerary[schedule][]">
<input type='text' name="itinerary[nightStay][]">
</div>
When you want to add a block of form with jQuery, use :
var idToAdd = $(".TextBox:last").attr("data-formNum")+1;
When you send this form to PHP, everything is going to be formated like :
Array
(
[intinerary] => Array
(
[dayNo] => Array
(
[0] => 15
[1] => 14
)
[cityName] => Array
(
[0] => London
[1] => Prague
)
...
Then you can write an INSERT INTO function cycling on this array like:
for ($i=0; $i < count($_POST['itinerary']['dayNo']);$i++)
{
$day = $_POST['itinerary']['dayNo'][$i];
$cit = $_POST['itinerary']['cityName'][$i];
}
Hope this helped.
Let me know if I misunderstood.

Categories