Extract dynamically created form data - php

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.

Related

How to insert Multiple records into mysql using php

i am fetching different record from the database but using single quantity field trying to insert multiple records into MYSQL but every time for loop or any other loop overriding single value in all rows(inserting single first value in every field), badly stuck. kindly suggest what kind of appropriate steps should be done.
<input type="text" name="qty[]" id="qtyid" style="width:40px;">
<?php
if(isset($_POST["update"])) {
$usersCount=count($_POST['qty']);
$qtys=implode(",",$_POST['qty']);
for($i=0;$i<$usersCount;$i++) {
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
$total=$total*$qtys;
?>
Your "question" is unclear. I read it couple times nad i still dont know what is your problem.
Anyway. I'll try to explain what your code do in case it would help you to understand where the problem is.
//if form was submited and input of name "update" was in
if(isset($_POST["update"])) {
// count array created by inputs of name="qty[]"
$usersCount=count($_POST['qty']);
// make a string from that array, separating the keys by a "," char
$qtys=implode(",",$_POST['qty']);
// loop as many times as number of elements in that array = <input name="qty[]"> you had in submited form
for($i=0;$i<$usersCount;$i++) {
// and finally, do always the same for each loop repeat
$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";
$dbh->query($query);
echo $qtys;
}
}
So in conclusion your loop is doing always the same - every each repeat:
`$query="UPDATE cart set qty='".$qtys."' WHERE prodid='$cartid'";`
Basically to do that you would't need to have loop.
Because in that query you change value of column qty wherever column prodid is equal to something

Checkbox Values stored in DB and want to display

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.

Dynamic forms and PHP

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
}

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

keep past value of variable

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?

Categories