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
}
Related
I'm not sure how to ask this question. It procedural question I believe.
<input type="hidden" name="1[]" value="dummy">
<input type="radio" name="1[]" value="5">
<label> Very Good </label>
<input type="radio" name="1[]" value="4">
<label> Good </label>
<input type="text" name="1[]" size="20">
<br>
<input type="hidden" name="2[]" value="dummy">
<input type="radio" name="2[]" value="5">
<label> Very Good </label>
<input type="radio" name="2[]" value="4">
<label> Good </label>
<input type="text" name="2[]" size="20">
$_POST output:
[1] => Array
(
[0] => Text misc
)
[2] => Array
(
[0] => 5
[1] =>
)
From this I construct and INSERT statement.
INSERT INTO coached_tracked (coached_id, value, note)
VALUES ($key, $value[0], $value[1]);
This is are dynamically generated form inputs. A radio button, text field pair.
How can I handle an occurrence where the radio is not selected and the text field has value, like in the first instance. I want the option of having nothing selected so a default value seems not called for. I tried with both with and without a dummy value (I saw an example suggesting a hidden field as a possible solution.)
Suggestions.
You should not tell the database what ID to use. Let the database itself determine that by using an auto-incremented column.
First, start with a logical input name. Using just numbers is extremely confusing and looking at your code, I have absolutely no idea what you're doing. We also want everything to go into the same PHP $_POST variable to not have to iterate over all possible number cominations. That means we can just iterate over the one single array.
Let's say you're adding a coach to a database, so logically we would start with:
<input name="coach">
Now when we want to add multiple coaches instead of just one, we can use HTML array names, however I would recommend you hard-code them instead of auto-incrementing in your HTML, which should simplify things later on. We also pluralize it to coaches:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>]">
<?php
}
Now if each coach contains a certain properties, let's say name, salary, note, etc, we can add the properties to the input names like so:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>][name]">
<input name="coaches[<?=$i?>][salary]">
<input name="coaches[<?=$i?>][note]">
<?php
}
Then in PHP you just iterate over $_POST['coaches'] and then use the properties for each coach how you wish:
if (isset($_POST['coaches'])) {
foreach ($_POST['coaches'] as $coach) {
$name = $coach['name'];
$salary = $coach['salary'];
$note = $coach['note'];
// Now execute the query:
// INSERT INTO coached_tracked (name, salary, note)
// VALUES ($name, $salary, $note);
}
}
Note: remember to sanitize any user-supplied data by using prepared statements with bound parameters to make sure you're not open to SQL injection attacks.
I can't get this to work. I need to update many records in 1 column, based on what's checked and filled out. I tried different combinations of checking and unchecking and having the text fields blank or not blank, and in this php post code i tried many different things, but can't figure out the correct combinations and if/elses or issets or empties, etc.
the values in the checkboxes correspond to record/row IDs. all the text boxes will be prefilled with prices. all the checkboxes will be dynamically checked or unchecked. a person can undo checked checkboxes if they want or check checkboxes that are not checked. on post, all the records that are checked should get the matching text box value.
the problem is i can't get the 2 arrays to match in my post. for example, in this sample set of fields, let's say i check the 2nd checkbox and the 4th checkbox. the records that should update and the values that should save into the column should be as follows...
2 -> 17.67
4 -> 19.84
but instead i get:
2 -> 16.95
4 -> 17.67
or this (if i remove the values from 1st and 3rd text boxes):
2 -> empty
4 -> 17.67
or this (2nd checkbox id and value missing completely)
4 -> 17.67
what am i doing wrong?
if (isset($_POST["savelist"]) && !empty($_POST["savelist"])) {
$productidcheckboxes = isset($_POST['productid']) ? $_POST['productid'] : array();
$listprices = isset($_POST['listprice']) ? $_POST['listprice'] : array();
//other things i tried
//$listprices = (empty($_POST['listprice'])) ? $_POST['listprice'] : array();
//$listprices = (!empty($_POST['listprice'])) ? $_POST['listprice'] : array();
//$productidcheckboxes = $_POST['productid'];
//$listprices = $_POST['listprice'];
$new = array();
for ($i=0; $i<count($productidcheckboxes); $i++) {
$new[] = $productidcheckboxes[$i];
$new[] = $listprices[$i];
}
$k=0;
foreach ($new as $value) {
$k++;
if($k==1){
$theid = $value;
}
if($k==2){
$thelistprice = $value;
//different ifs i tried
//if ($theid<>"")
//if ($value<>"")
//if ($theid<>"" && $thelistprice<>"")
//if ($theid<>"" && $value<>"")
if ($thelistprice<>"")
{
echo $theid.": ";
echo $thelistprice."<br>";
//update table with the list prices
//mysql_query("UPDATE table_name SET mylistprices = '$thelistprice' WHERE id = $theid");
}
$theid = "";
$thelistprice = "";
$k=0;
}
}
}
form looks like this
<form action="" method="post">
<input type="checkbox" value="1" name="productid[]">
<input type="text" value="16.95" name="listprice[]">
<input type="checkbox" value="2" name="productid[]">
<input type="text" value="17.67" name="listprice[]">
<input type="checkbox" value="3" name="productid[]">
<input type="text" value="18.81" name="listprice[]">
<input type="checkbox" value="4" name="productid[]">
<input type="text" value="19.84" name="listprice[]">
<input type="checkbox" value="5" name="productid[]">
<input type="text" value="16.85" name="listprice[]">
<input type="submit" value="Save List" name="savelist">
</form>
by the way, by uneven i mean all the checkboxes will have values so correct rows will be updated, but the text boxes may or may not be filled. i would like it if i didn't have to clear any values in checkboxes or text inputs. it should just update records that are checked with it's corresponding values, and ignore non-checked checkboxes and the non-checked checkboxes corresponding values. but in the end, i may have to change how it's done, but i can't solve this one.
Add hardcoded numeric values to the form names so they match up in your processing page. Right now they are random:
<form action="" method="post">
<input type="checkbox" value="1" name="productid[1]">
<input type="text" value="16.95" name="listprice[1]">
<input type="checkbox" value="2" name="productid[2]">
<input type="text" value="17.67" name="listprice[2]">
<input type="checkbox" value="3" name="productid[3]">
<input type="text" value="18.81" name="listprice[3]">
<input type="checkbox" value="4" name="productid[4]">
<input type="text" value="19.84" name="listprice[4]">
<input type="checkbox" value="5" name="productid[5]">
<input type="text" value="16.85" name="listprice[5]">
<input type="submit" value="Save List" name="savelist">
</form>
Now you know if the user checks product[4], it really is product[4]. When you leave your keys blank like productid[], that is just an anonymous spot in the array and makes it impossible to track when dealing with checkboxes that have no value unless checked.
If you check off productid[2] and productid[4] you know that the values in the listprice array are the values that go with what you have checked off:
Array
(
[listprice] => Array
(
[1] => 16.95
[2] => 17.67
[3] => 18.81
[4] => 19.84
[5] => 16.85
)
[productid] => Array
(
[2] => 2
[4] => 4
)
)
To access the values, loop through the productid but access the listprice:
foreach($_POST['productid'] as $key => $value){
echo $_POST['listprice'][$value].'<br />';
}
I have three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.
I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}
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.
We have a zend form with text input fields and array of checkboxes, as shown below -
<input class="checkbox_Category" type="checkbox" name="tag[]" value="19"> somename1 <br/>
<input class="checkbox_Category" type="checkbox" name="tag[]" value="20"> somename2 <br/>
<input class="checkbox_Category" type="checkbox" name="tag[]" value="21"> somename3 <br/>
and using a
$formObject->populate($formDataArray);
in the controller to populate data in the whole form. All the text input fields seem to populate fine, but the checkboxes don't. Int the $formDataArray, the data for the checkboxes is in the format
[tag] => Array ( [0] => 20 [1] => 19 )
Along with the other form data like - [firstName] => 'somename' etc.
I am not able to figure out the format of the data the form is expecting, in order to get populated with populate();
hi might be problem with the name you have given as array please change like below
<input class="checkbox_Category" type="checkbox" name="tag" value="19"> somename1 <br/>
<input class="checkbox_Category" type="checkbox" name="tag" value="20"> somename2 <br/>
<input class="checkbox_Category" type="checkbox" name="tag" value="21"> somename3 <br/>
Please let me know if i can help you further
Without actually seeing your Zend_Form code, this is very difficult. However, most often, I've seen people mistake the 'checkbox' element with the 'multiCheckbox' element in Zend Framework. I know - it's a bit confusing - but checkbox is a single checkbox with an on/off value. MultiCheckbox handles multiple values - and I think it's what you are trying to accomplish. Let me show you a quick form that will work and generate your HTML above.
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$multiOptions = array(
19 => 'somename1',
20 => 'somename2',
21 => 'somename3'
);
$this->addElement('multiCheckbox', 'tag', array(
'multiOptions'=>$multiOptions
));
$this->addElement('submit', 'submitbutton');
}
}
Now, if you use something like...
$form->populate($this->getRequest()->getPost());
in your controller, it will populate as expected.
Hope this helps!