PHP loop through array of HTML textboxes - php

I have an HTML form with a dynamic number of checkbox fields, all of which are encapsulated within a submit form. When the form is submitted, I want to loop through the values of each checkbox field with a PHP script. At the same time, I have to keep a certain ID associated with the checkbox field so that when I loop through each one in my script, I can use the ID to update the correct row in my database. Currently, I have:
<input checked="checked" name="attended_<?php echo($pid); ?>"
I'm just not sure how to go ahead and access all of the attended[] values from my PHP script (and keep the ID at the same time). Would I use a multidimensional array like the following?
<input checked="checked" name="attended[<?php echo($i); ?>][<?php echo($pid); ?>]; ?>"
I'd appreciate any help on this. Thanks!

lets say this is data from form
<input checked="checked" name="attended[1]; ?>"
<input checked="checked" name="attended[2]; ?>"
<input checked="checked" name="attended[3]; ?>"
<input checked="checked" name="attended[4]; ?>"
<input checked="checked" name="hello[1]; ?>"
<input checked="checked" name="hello[2]; ?>"
this is how it would look as array. not needed its just for show
// $k => $v
$attended[1]='blah blah';
$attended[2]='blah blah';
$attended[3]='blah blah';
$attended[4]='blah blah';
$hello[1]='blah blah';
$hello[2]='blah blah';
science bit
foreach($attended as $k=>$v){
$sql = "UPDATE mytable SET attended = '$v', hello = '{$hello[$k]}' where id = '$k'";
$query = mysql_query($sql) or die("Cannot query the database.<br />" . mysql_error());
}
all associated data should have same pid e.g
<input checked="checked" name="attended[1]; ?>"
<input checked="checked" name="hello[1]; ?>"

Usually when I create checkboxes I put an index in the name. This way you can loop through each checkbox in your submittion code.
<input type="checkbox" name="cbGroup[1]" value="y" />
<input type="checkbox" name="cbGroup[2]" value="y" />
<input type="checkbox" name="cbGroup[3]" value="y" />
and in your PHP
foreach($_POST['cbGroup'] as $index=>$checkbox) {}
You'll want to make sure your $_POST['cbGroup'] is set though because it won't be if the checkbox isn't checked.
Edit: Sorry, I should learn to read the question fully heh :) I use multidimensional arrays in PHP with HTML inputs all the time and I think it's the way I would go.

Maybe you could do it with a hidden field which is sort of 'associated' with the checkbox by the name:
<input checked="checked" name="attended_<?php echo($i); ?>"
<input type="hidden" name="attended_<?php echo($i); ?>_reference" value="<?php echo($pid); ?>" />
So while processing the POST-data after a submit, you could put the references together again with some string-manipulation.

Related

Combine form values under one name using GET method

I have a form using the GET method consisting of checkboxes.
This form is sending data to another page that is receiving the GET info and using it to pull info from a json api. I need to have it send the name once with all values combined into one string like this: example.com/color=RedGreenBlue
I am able to get all values combined and echoed onto the page but because they are in a foreach loop I am not able to pass them in the form. I tried below using the hidden field to pass them with no luck.
This is the method I've seen suggested but does not work for me:
<form action="" method="get">
Red<input type="checkbox" name="color[]" value="Red">
Green<input type="checkbox" name="color[]" value="Green">
Blue<input type="checkbox" name="color[]" value="blue">
<input type="submit" value="submit">
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
foreach ($name as $color){
echo $color;
}
}
?>
<input type="hidden" name="MajorArea" value="<?php echo $color; ?>" />
</form>
Is there a way to assign one name to a group of checkboxes? Is there a way to pull the foreach loop data and use it outside a loop? Am I overlooking a way that is much easier than this?
Thanks for any advice!
I'll go out on a limb here and delete if it isn't what you're after. $_GET['color'] will be an array or it will be empty. You could also use isset:
<form action="" method="get">
Red<input type="checkbox" name="color[]" value="Red">
Green<input type="checkbox" name="color[]" value="Green">
Blue<input type="checkbox" name="color[]" value="blue">
<input type="submit" value="submit">
</form>
<?php
if (!empty($_GET['color'])) {
echo implode($_GET['color']);
}
?>

Posting array of checkboxes in PHP

I have multiple checkboxes with names of adminMeta[], such as:
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
and so on and I also have text inputs like this too with the same names.
When the data is posted, I am looping through using a foreach loop:
foreach($_POST["adminMeta"] as $a => $b) {
}
inside the loop, I add/update the record in my database depending on whether it exists already or not.
But I am having some issues with checkboxes and knowing whether they are checked or not.
I have tried using if(isset($b)) but that hasn't worked.
How can I tell inside my loop, whether a checkbox is checked or not?
If a checkbox is not checked, then it is not a successful control.
If it is not a successful control, then it won't be included in the form data at all.
If it isn't in the form data, then it won't appear when you loop over the form data.
So
If it is in the form data, then it is checked
Otherwise it is not checked
Normally I'd approach this problem with something along the lines of:
$list_of_checkboxes = [ "name1", "name2" ];
Then generate the form with:
foreach ($list_of_checkboxes as $name) {
?>
<label>
<input type="checkbox"
name="adminMeta[]"
value="<?php echo htmlspecialchars($name); ?>">
<?php echo htmlspecialchars($name); ?>
</label>
<?php
}
Then test the data with:
foreach ($list_of_checkboxes as $name) {
if (in_array($name, $_POST['adminMeta'])) {
# Checked
} else {
# Not checked
}
}
Another approach would be to set hidden inputs before each check with default value of 0:
<input type="hidden" name="adminMeta[name1]" value="0" />
<input type="checkbox" name="adminMeta[name1]" value="1" />
<input type="hidden" name="adminMeta[name2]" value="0" />
<input type="checkbox" name="adminMeta[name2]" value="1" />
Now you will receive the data even if you don't check the checkboxes.

Use database to check a checkbox

I have a page to view assets with an Edit link. When I click the link it goes to edit_case.php which has a form to edit what elements of the row are in the database as checkboxes. However the boxes do not show them as checked. I have the following code...
// get already checked box values
$repop = "SELECT * FROM case_audit WHERE case_id = $case_id";
$popresults = mysqli_query($dbc, $repop);
$row = mysqli_fetch_array($popresults, MYSQLI_ASSOC);
print_r ($row);
The print_r does show the whole record row from DB. which is either a 1 or 0, checked || not checked.
The form...
<div id="facepics">
<label><input type="checkbox" name="Facial1" value="<?php echo $row['frontrest']; ?>" >Front at Rest </label><br>
<label><input type="checkbox" name="Facial2" value="<?php echo $row['frontbigsmile']; ?>" >Front Big Smille</label><br>
<label><input type="checkbox" name="Facial3" value="<?php echo $row['profile']; ?>" >Profile</label><br>
<label><input type="checkbox" name="Facial4" value="<?php echo $row['subvertex']; ?>" >SubMento Vertex</label><br>
</div>
I know I need to turn the 1's to "checked" just not sure how best to do that.
so basically checked="true" attribute in input creates a checked checkbox.
HTML Code looks like
<input type="checkbox" checked="true">
In your case you can do it like:
<input type="checkbox" name="Facial1" value="frontrest" <?= (intval($row['frontrest']) == 1) ? 'checked' : '';>
Also note that I changed value attribute, with frontrest so that you can identify the checkbox uniquely
EDIT: I have modified the code
<input type="checkbox" name="Facial1" <?=$row['frontrest']==1?'checked':''?>>
I often have the same issue where the browser ignores checked="false" and checks all
so I use
<input type="checkbox" checked>

combine checkbox values using php mysql

I having around 20 check boxes in my form as
<input type="checkbox" name="c1" value="1" />
<input type="checkbox" name="c2" value="2" />
<input type="checkbox" name="c3" value="3" />
<input type="checkbox" name="c4" value="4" />
i would like to these values to a database. I just thought rather than creating 20 fields in my database grab all the values at store in the db as 1,2,3,4 and then when querying to explode the values and display it accordingly using php.
can someone please tell me how am i supposed to concatenate the values 1,2,3,4 from the check fields when submitted so i can pass to the database.
i would appreciate if anyone can suggest a different effective way to achieve this using php.
You can change the name of the checkboxes to be the same, something like
<input type="checkbox" name="cb[]" value="1" />
<input type="checkbox" name="cb[]" value="2" />
Then access them via $_GET or $_POST via
if (isset($_POST['cb'])) {
$my_values = implode(",", $_POST['cb']);
}
If you want them sorted, then you will want to do something like this:
if (isset($_POST['cb'])) {
$my_values = $_POST['cb'];
sort($my_values);
$my_db_value = implode(',', $my_values);
}
For the record, I agree with #Shef in the case that the database can handle the extra load. Depending on when this information will be needed in a highly scalable solution, however, this is a perfectly acceptable way to handle this.
To answer your initial question, first off you need to name your checkboxes all the same name, so:
<input type="checkbox" name="box[]" value="1" />
....
<input type="checkbox" name="box[]" value="20" />
PHP script:
$boxes = $_POST['box'];
$values = implode(",", $boxes); // $values now has "1,2,3,4...", insert into table
A better way would be to have a separate table (see #Shef 's comment).

Checkbox "checked"-value jumps up to earlier array values, when array is empty

I have an array of checkboxes name="box[]". Through PHP I make sure that they're checked after they're submitted by echoing "checked='checked'" if they were checked at submit event.
Now, if I check the third box, the value jumps down to the first checkbox after submit, since the array was empty up until the third checkbox. Same, if I check the 2nd and 3rd checkbox, they jump down to 1st and 2nd after submit. This is the code I'm using:
<form method="post">
<input type="checkbox" name="box[]" value="true" <?php if ($box[0] == true) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="true" <?php if ($box[1] == true) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="true" <?php if ($box[2] == true) echo "checked='checked'"; ?>><br>
<p>
<input type="submit" value="Submit">
</form>
Try it at:
http://experiencerapanui.com/selecttest.php
Can I make the checkboxes fill up the array with a value "false" or whatever, if the box is unchecked? Which way should I go?
****** EDIT ******
Thanks to phant0m, I managed to come up with a solution:
<form method="post">
<input type="checkbox" name="box[]" value="1" <?php if (in_array("1", $box)) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="2" <?php if (in_array("2", $box)) echo "checked='checked'"; ?>><br>
<input type="checkbox" name="box[]" value="3" <?php if (in_array("3", $box)) echo "checked='checked'"; ?>><br>
<p>
<input type="submit" value="Submit">
</form>
Putting unique values for the checkboxes, then if I find the value in the array $box[], the box is marked as checked.
This does not work, because only those checkboxes, that are checked, are being put into the $box array.
Either use different names, or different values to distinguish between them.
Consider this: You check the second and the third checkbox. In PHP, you will receive:
$_POST['box'] = array(0 => "true", 1 => "true");
You cannot know, which checkboxes have been checked, unless all of them are.
The POST value should start with isset, then !empty($array) determines if the POST value is an array and prevents a null array error when no options are selected.
&& is_array($_POST['box']) could be used in addition to !empty($_POST['box']) as well to check the validity of the array.
A variable is used in the following examples for the value field, as it makes it easier to define and populate inputs when using a foreach loop and may be sanitized if needed as a preventive measure.
It would probably be a good idea to sanitize the $_POST array also, and enclosing it in a function with the validation would allow it all to be called from the checkbox input and keep the input area tidy.
<input type="checkbox" name="box[]" value="<?php echo $unique_id; ?>" <?php if(isset($_POST['box']) && !empty($_POST['box']) && in_array($unique_id, $_POST['box'])) echo "checked='checked'"; ?>>
OR
<input type="checkbox" name="box[]" value="<?php echo $unique_id; ?>" <?php my_function(); ?>>
Excellent question and solutions! There seem to be relatively few examples that use an array method to preserve Post selections, and the one provided here is relevant and very helpful even years later.

Categories