Dynamically created checkbox list then POST retrieval on another page.
First off, Thanks in advance.
A couple questions regarding best practices with the checkboxes in a form and then $_POST.
Family picture album stuff. I am getting an array back from my brothers database and putting it in a loop.
Question 1-
Is it best practices when wanting to retrieve this information on another page to have the "name" be the familyPictureID or should I put that in the "value"?
Sample of table element inside a loop:
<td data-label="Active">
<input class="checky" type="checkbox" name="cList[<?php echo $row['familyPictureID']; ?>]"
<?php if($row['active']==1) { echo 'value="1" CHECKED>';
} else { echo 'value="0">'; }
?>
</td>
Question 2-
When retrieving this information on a secondary page, how do I get all the values from the checkboxes? I want to know if they are checked or not but also pair that up with the 'familyPictureID'. Is that correct and best practices?
I am trying to get them like so:
if(!empty($_POST['cList'])) {
echo "check box test <pre>";
print_r($_POST['cList']);
echo "</pre>";
foreach($_POST['cList'] as $familyPictureID) {
echo "check=$familyPictureID<br>";
}
}
I would then send this back to my brothers database with an UPDATE to these family pictures whether they are checked or not.
Does this make sense?
Thanks in advance. I searched for something similar but people on here are doing some complicated stuff that seems way beyond the scope of what I am trying to do.
Thanks!
-MT
You can do it either way. If you put the ID in the name, then you can write:
foreach (array_keys($_POST['cList']) AS $id) {
echo "check=$id<br>";
}
If you put the ID in the value, you would write:
foreach ($_POST['cList'] AS $id) {
echo "check=$id<br>";
}
Only boxes that are checked get sent to the server, so both of these will iterate over the checked boxes.
If you have other input fields that are also arrays based on the ID, then for consistency I would recommend doing the same thing with the checkboxes.
Related
This question is basically for my understanding, so kindly guide me. I dont require any code but just the approach for solving this type of problem.
I am using jquery to dynamically add form elements. For example, I want user to enter his favourite movie. I have given him an add button to add more movies. Now if user adds 10 times for 10 movies, how will i save this data to database ? i mean i will have only one column for movie but user is entering 10 (some might add 100) so how is this data stored ?
I have asked this question to basically understands how to save data when the form elements are dynamically added ? shall i save them to column movies and seperate them by commas or something else ?
There are many approach to solve this problem. One solution to this is AJAX. say example you are using php
1) Sort form data with each use press button; jQuery Form.
2) a php function to process sql queries.
3) call php function in ajax in success method.
4) store value in database.
In the form elements that you add, you would make the name= value into an array, so that the various identical items could be processed.
For example, suppose you are cloning a table row. Suppose this is the template row that you are cloning:
<tr>
<td>
Movie Name: <input type="text" name="mov[]" />
</td>
</tr>
After the form was posted, the data would appear something like this:
POST DATA:
Array
(
[mov] => Array
(
[0] => (the initial, template row would have no value)
[1] => Gladiator (whatever user typed in)
[2] => Troy (the next movie entered by user...
The code I used to view the POST output above looks like this:
If (empty($_POST)===false) {
echo '<pre>';
echo 'POST DATA:<br />';
print_r($_POST);
echo '<br />*********************************************************<br /><br />';
echo 'UPLOADED FILES:<br />';
print_r($_FILES);
echo '</pre>';
die('Dying immed inside IF EMPTY($_POST)===FALSE...');
}
I have a drop down list on page one with select code:
print "Select week for season 1: <select name='Week_select'> <br>";
On page 2 I have
$varWeek=$_POST['Week_select'];
Then another drop down list:
print "Select a team that played season 1and week $varWeek: <select name='Team_select'><br>";
So far so good and many thanks to all who have gotten me this far.
Now when I go to page 3, I lose $varWeek
I see that I should either use a $_GET or pass it as hidden.
I tried $varWeek=$_GET['Week_select'];
but that didn't work.
I am unsure how to pass it hidden. Please help me understand a little more.
Many thanks in advance
A better approach would be to register those variables as session variables. This way they won't show up in the URL and you will be able to access them across several pages. Have a read here:
http://www.php.net/manual/en/intro.session.php
You can access/store a session variable like this:
$_SESSION['varname'] = 'value';
and on another page
var_dump($_SESSION['varname']);
Add the variable into the form, like you said, as a hidden field, like so:
print '<input type="hidden" name="Week_select" value="'. $_GET['Week_select'] .'" />';
Then on the page which handles the form, the variable will be available in $_POST['Week_select']
I am having a form with quite a lot of list boxes. After submitting the form I have no problem to process all list boxes with PHP in a loop. But I am looking for a way to only grab those that have changed because it would save a lot of processing time.
Let's say I have a hundred list boxes. Their ids are "lb_1" ... "lb_100". I would loop through them like:
foreach($_POST as $key=>$value) {
if (substr($key,0,3)== "lb_" ) {
...do something...
}
}
That loop however will do something with all the hundred listbox values. I only want to catch those that have actually changed.
Any ideas?
To expand on the suggestion given by #Tushar, you could use Javascript to set the Disabled attribute to true for any field that has not changed. That way they would not exist in the POST. The only way you would know which ones to disable is to store the initial values (in JS probably for ease of comparison). Then on form submit, loop through the fields and disable all the ones that have not changed.
document.getElementById('lb_1').disabled = true; // example of how to disable field
I can provide more example code if you like.
Ok, thanks to your tips I came up with this client-side solution:
I added a hidden form text field right before each listbox that contains the original value. The hidden field and the list boxed are named with the same unique suffix so I know which one belongs to which.
When the form is passed the PHP loop looks like this:
foreach($_POST as $key=>$value) {
if (substr($key,0,3)== "lb_" ) {
if ($_POST[hidden_name] != $value) {
setNewValue($value);
}
}
}
This is a lot faster than accessing the database for each compare since the values are already available in the $_POST array.
Thanks for your help.
I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?
You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc
Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.
The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>
I have web page in PHP which displays all records in a table. I want to add check boxes against all rows and user can check a check box to select a row and then submit the page. When the page is submitted I want to enumerate all check boxes and check whether they are checked or not, How can I do this?
You'll create your checkboxes like this:
<input name="rows[]" value="uniqueIdForThisRow" type="checkbox" />
<input name="rows[]" value="anotherId" type="checkbox" />
Then you can loop through them like this:
<?php
// $_POST['rows'] contains the values of all checked checkboxes, like:
// array('uniqueIdForThisRow', 'anotherId', ...)
foreach ($_POST['rows'] as $row) {
if ($row == 'uniqueIdForThisRow') {
// do something
}
}
?>
PHP docs on dealing with forms, see especially Example #3.
Creating the form
You can generate the HTML as follows:
<form [action, method etc]>
<table>
<?php
foreach($dataSet as $dataRow) :
?>
<tr>
<td>
<input type="checkbox" name="dataRow[]" value="<?=$dataRow['id']?>"/>
</td>
[Additional details about datarow here]
<tr>
<?php
endforeach;
?>
</table>
</form>
AFTER POST
look into $_POST['dataRow'] : this will be an array with values the IDS of your $dataRow, so using array_values on $_POST['dataRow'] will give you all the ids of the selected rows:
<?php
$checkedRows = array_values($_POST['dataRow']);
foreach($checkedRows as $row) {
// Do whatever you want to do with the selected row
}
You don’t have to check all checkboxes if they have been checked. Because only successful controls are send to the server. And a checkbox is only successful when it’s checked:
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
So you just have to look what checkboxes you get in the request at all. And if you want to use <select multiple>, take a look at How do I get all the results from a select multiple HTML tag? in the PHP FAQ.
if i were you... i wouldn't fight with altering html table structure.
you can handle that with Javascript frameworks like JQuery which is very effective solution for you. you deal only a few lines of JS code and you don't need exaggerate the html output (i guess it's probably long enough). about jquery there is a good source named visual jquery if you have never used that.
here is the way how to do that.
you dont need to edit inside the loop. you just only put an id to your table tag.
then add new column to your table with checkboxes inside.
then you can get the values of checkboxes & serialize them in to a hidden input. or you can handle selected rows with ajax easy. i think JS framework will work better.
normally i've added many links to post but it says it's not allowed for new users.