Ive started working on a dynamic form script that allows a user to add form elements via Jquery, which is then in turn submitted to a PHP script.
I'm just after some feedback on ways to achieve this. At the moment I have the following:
When a user adds a form element the element is added with the following name array:
<textarea name="element[text][123]">
<input type="text" name="element[input][456]" />
As I need to know the type of form element that was submitted I am using a multidimensional array called 'element[][]' where the first level of the array is the type of element and the second element of the array is a unique ID and the value.
When I var_dump() This after submission PHP outputs:
array
text => array
123 => string 'The textarea value'
input => array
456 => string 'The input field value'
Im working on the PHP side of the script now and just wondering if there is a better way to do this.
Any thoughts?
UPDATE
I have to change the way that Im doing this as the array keynames are not unique.
If the user adds two textareas
<textarea name="element[text][123]">
<textarea name="element[text][456]">
When the user adds a form element, the element can be dragged so the positioning can be changed after the element was created. This allows a user to add an element but then move it to where they want it to appear.
PHP handles this ordering fine and accepts the array in the order that the form is submitted, however as mentioned above if the key names are the same then the order will be broken.
On the PHP side I need to know
the type of form field
the value of the form field
the unique ID, which is just a timestamp, of the form field
I think I might need to do what Cole mentioned, assigning the names as:
element[text_123]
I can then explode the keyname on '_' to determine the type and the identifier.
UPDATE
I took the script Jack posted and slightly modified it
$vars = $_POST['element'];
foreach ($vars as $id => $vals)
{
// $vars[id] outputs the ID number
// $vars[vals] is the array containing the type and value
echo "This fields ID is $id. ";
foreach($vals as $key => $value)
{
echo "Type was: $key and the value was: $value <br />";
}
}
A quick test of this outputted
This fields ID is 1338261825063. Type was: heading and the value was: xzczxczxczxczxczxc
This fields ID is 1338261822312. Type was: heading and the value was: asdasdasdasdad
From this I know the identifier and the array that it belongs to, the type and the value, but I also know the order that the data was submitted.
From that I can wrap my data in markup, perform any additional operations and then insert the data into the database.
Looks okay; you could also consider something like this (it introduces more fields though, so you must really think the benefit is worth it):
<input type="hidden" name="element[123][type]" value="text" />
<input type="hidden" name="element[456][type]" value="input" />
<textarea name="element[123][value]">
<input type="text" name="element[456][value]" />
Then you can do this:
foreach ($_POST['element'] as $name => $info) {
// $info['type'] is 'text' or 'input'
// $info['value'] is the user input
}
Related
In my extremely limited development experience, when I submit a form, usually the name or ID of an input value corresponds with a column in a MySQL table and the name of both the name/ID and column are known. But I have what amounts to an order form where I have a number input and assign the name/ID a unique ID from a table that has all the available items. How can I submit the input name or ID along with its value when I am dynamically populating the name/ID?
Example:
<?php '<input type="number" name="'.$row['itemID'].'" id="'.$row['itemID'].'">';?>
Table Structure I would like to insert into has the following columns:
itemID
quantity
The itemID would be posted from the name of the input field and the quantity would be the value of the input field as entered by the user.
Any guidance is much appreciated. Thanks!
You could use a foreach($_POST as $id => $value) loop and get the key, but then you'd never be able to use any other input values besides the ones named with an item ID.
SOLUTION: With the following method, you can use any other inputs you want inside the form:
<input type="number" name="products[<?php echo $row['itemID']; ?>]" id="<?php echo $row['itemID']; ?>" />
Now in your php, you can access $_POST and it will look like this:
[
'products' => [
'123' => 4,
'456' => 1,
...
]
]
Now you can loop through $_POST['products'] in a foreach without worrying about other input values.
foreach($_POST['products'] as $id => $num_purchases)
{
//stuff
}
I am not sure if I have understood you correctly but may be you need a hidden input array to store all names from $_POST;
echo '<input type="hidden" name="allNames[]" value="'.$row['itemID'].'">';
Later in your code after post:
$all_names = $_POST['allNames'];
foreach($all_names as $key => $value) {
echo $_POST[$value]; //Take the user input
}
Please see this link
http://thedesigningworld.com/bea
Here's a Small form contains 8-9 fields + a group of checkboxes
I want to save all details in DB + want to display in a table in proper manner, but it not works properly
Here's the code which i used
for($i=0;$i<count($_POST[wert1]);$i++)
{
if($_POST[wert1][$i]!= "")
{
$check1[] =$_POST['wert1'][$i]; } }
$new1=implode(',', $check1);
$result = "INSERT into table1(check1) values($new1)";
$result = mysqli_query($con, $result);
So i've one doubt that for each checkbox row, should i need to define same array name or different like here i used array name as wert1[] for first row
Checkbox values are not transmitted if the box is not checked.
If you have influence, you could put a hidden input field of the same name before the checkbox and the value "0", like:
<input type="hidden" name="checkbox_name" value="0" />
<input type="checkbox" name="checkbox_name" value="1">Some Text</input>
In you example site, you're using array notation, which is basically a good thing. However, you have not given an index so you might not recognize missing elements.
I put a variable (price) to a html form from database.
then user changes the price and submit the form and variable is updated in database.
I want to keep previous value (last state and show it in the form) but if I update the form variable keeps updating.
What is best way to remember previous value of variable (in array for example) ?
If you're updating this data in an actual Database, you should create a parallel table that holds the value of the previous row.
Otherwise, if you're updating only an array, you can just create a copy prior to updating the array: http://codepad.org/SvlasJ7f
<?php
$array = array('Old Value');
$lastarray = '';
updateArray($array,'New Value');
function updateArray(&$a,$v) {
$GLOBALS[lastarray] = $a;
$a = array($v);
}
?>
If you want to retain the LAST value AND display it on the screen, combine the two! Just display the previous value, in a readonly input field in your form. That way, you will still have the previous value every time the form is submitted.
<form action="process.php" method="POST">
<input type="text" name="Current" value="...">
<input type="text" name="Last" value="..." readonly="readonly">
</form>
Or am I missing something?
I've just started using jQuery. One thing I've been using it for is adding rows to a table that is part of a form.
When I add a new row, I give all the form elements names like 'name_' + rowNumber. I increment rowNumber each time I add a row.
I also usually have a Remove Row Button. Even when a row is removed, the rowNumber count stays the same to keep from repeating element names.
When the form is submitted, I set a hidden element to equal the rowNumber value from jQuery. Then in PHP, I count from 1 to the rowNumber value. Then for each value, I perform an isset($_REQUEST['name'_ . index]). This is how I extract the form elements that remained after deleting rows in jQuery.
Does anyone here have a better technique for accounting for deleted rows?
For some of our simpler tables, we use a field name such as 'name[]', though for JavaScript they would need a usable id.
It does add some complexity in that 'name[0]' has to assume 'detail[0]' is the correct element.
PHP will create an array and append elements if the field name ends with [] similar to
<input name="field[]" value="first value" />
<input name="field[]" value="second value" />
// is roughly the same as
$_POST['field'][] = 'first value';
$_POST['field'][] = 'second value';
Use arrays to hold you values in your submission. So bin the row count at the client side, and name your new elements like name[]. This means that $_POST['name'] will be an array.
That way at the server side you can easily get the row count (if you need it) with:
$rowcount = count($_POST['name']);
...and you can loop through the rows at the server side like this:
for ($i = 0; isset($_POST['name'][$i]; $i++) {}
You could extract all the rows by doing a foreach($_POST as $key => $value).
When adding a dynamic form element use the array naming method. for example
<input type="text" name="textfield[]" />
When the form is posted the textfield[] will be a PHP array, you can use it easily then.
When you remove an element make sure its removed from the HTML DOM.
Like blejzz suggests, I think if you use $_GET, then you can just cycle through all of the inputs that were sent, ignoring the deleted rows.
foreach ($_GET as $k=>$v) {
echo "KEY: ".$k."; VALUE: ".$v."<BR>";
}
I notice that you mention "accounting for deleted rows"; you could include a hidden input, and add a unique value to it each time someone deletes a row. For example, the input could hold comma-separated values of the row numbers:
<input type="hidden" value="3,5,8" id="deletions" />
and include in your jQuery script:
$('.delete').click(function(){
var num = //whatever your method for getting the row number
var v = $('#deletions').val();
v = v.split(',');
v.push(num);
v = v.join(',');
$('#deletions').val(v);
});
Then you should be able to know which rows were deleted (if that is what you were looking for).
you can use POST or GET
After submit you can use all of your form element with this automaticly. You dont need to reorganise your form element names. Even you dont need to know form elements names.
<form method="POST" id="fr" name="fr">.....</form>
<?php
if(isset($_POST['fr'])){
foreach($_POST as $data){
echo $data;
}
}
?>
Also you should look this
grafanimasyon.blogspot.com.tr/2015/02/veritabanndan-php-form-olusturucu.html
This is a automated form creator calcutating your database tables. You can see how to give name to form elements and use them.
i have a database patient with 3-4 tables n each table has about 8 attributes....
i have a table medical history which has attribute additional info ... under which i have 5 checkboxes....
all the values entered are taken up except the chekbox values.....
plz help
How are you constructing your fields? Do they all have the same name attribute? Do they have a name attribute at all? Is there a value attribute?
<input type="checkbox" name="testfield" value="somevalue" />
<input type="checkbox" name="testfield" value="othervalue" />
If you're constructing the checkboxes like that, then PHP will by default ignore all but the last value submitted (it overwrites previous values with new ones), like this:
$_POST = array(
'testfield' => 'othervalue'
)
You have to force PHP into 'array mode' for this type of construct, by adding [] to the name attribute:
<input type="checkbox" name="testfield[]" value="somevalue" />
<input type="checkbox" name="testfield[]" value="othervalue" />
This will allow multiple values to be submitted under the same name, and you'll end up with an array in your _GET/_POST arrays:
$_POST = array(
'testfield' => array('somevalue', 'othervalue')
)
Of course, only the checkboxes which are actually checked will be sent with the form data.
Check that your form is properly constructed by putting a var_dump($_POST); (or GET or REQUEST) in the form handling part of the script and see if the checkbox values are actually being sent. Perhaps you're looking for the wrong name attribute, the tags could be malformed in the form, etc...