PHP:
if (isset($_POST['checkbox'])){
foreach ($_POST['checkbox'] as $x){
array_push($arr, judgeNametoID($x));
}
}
I've been getting errors when there's only one checkbox selected. If I keep the isset() in there, I don't get errors, only the checkbox selected is not added to the array.
Why is $_POST['checkbox'] not getting set if there's only one checkbox selected?
PHP/HTML of page with the checkboxes:
echo '<ul>';
$list = getActiveJudges();
foreach ($list as $x){
$found = 0;
foreach ($arr as $y){
if ($x == $y){
$found = 1;
break;
}
}
if ($found==1){
echo '<li>';
array_push($selectedJudges, judgeNametoID($x));
echo '<input type="checkbox" checked="checked" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>';
echo '</li>';
}
else {
echo '<li>';
echo '<input type="checkbox" named="unchecked[]" value="'.$x.'" />'.$x.'<br/>';
echo '</li>';
}
}
echo '</ul>';
Errors when I remove the isset():
Notice: Undefined index: checkbox in c:\Inetpub\wwwroot\CaseManagement\changeuserjudgeprocess.php on line 11
Warning: Invalid argument supplied for foreach() in c:\Inetpub\wwwroot\CaseManagement\changeuserjudgeprocess.php on line 14
Is the input name actually checkbox?
If you want to iterate through a list of checkboxes, you'll need html like this
<input type="checkbox" name="checkbox[]">
<input type="checkbox" name="checkbox[]">
<input type="checkbox" name="checkbox[]">
But that doesn't help very much as you won't know which checkbox was checked, so you could try something like
<input type="checkbox" name="checkbox[checkbox1]">
<input type="checkbox" name="checkbox[checkbox2]">
<input type="checkbox" name="checkbox[checkbox3]">
and then loop through like so:
if(isset($_POST['checkbox'])){
foreach($_POST['checkbox'] as $checkboxID => $checkboxVal){
// $checkboxID will be checkbox1, checkbox2, checkbox3 as specified above.
// $checkboxVal will always be 'on'
}
}
Of course, you may already have html like this, if so, we'll need to see it in order to help more :)
Maybe what you checked is the checkbox which the name is 'unchecked[]'
By the way, it is not necessary to give the unchecked checkbox a differernt name.
Related
I have 5 check boxes from which a user can select one or more choices. The selected choices are then updated in database. The user's choices are then displayed/reviewed on another page. However my issue is that I want to show the updated choices together with the non-selected choices when doing a foreach loop in PHP.
These are the 5 check boxes
<input type="checkbox" name="interest[]" value="fishing">Fishing
<input type="checkbox" name="interest[]" value="camping">Camping
<input type="checkbox" name="interest[]" value="hiking">Hiking
<input type="checkbox" name="interest[]" value="swimming">Swimming
<input type="checkbox" name="interest[]" value="running">Running
<br><br>
<input type="submit" name="submit" value="Submit">
Heres the code that updates
if (isset($_POST["submit"])) {
$interestArr = $_POST['interest'];
$interest = new Interest();
$newArr = implode(',', $interestArr);
$interest->updateInterests($id=19, $newArr);
}
Heres the code that displays
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
foreach ($newArr as $data) {
echo '<input type="checkbox" name="interest[]" value="'.$data .'" checked>'.$data;
}
The update choices are stored under the interests column in DB like so
fishing,camping,running
And the foreach loop displays them checked check box with the correct corresponding labels.
How can I display the other check boxes that were not selected just so that the user might want to make changes?
Thanks.
Here's a simple example to illustrate the main idea. This code is intended to run in the single script.
The main ideas are:
Use a global list of interests to drive the form.
Keep a separate global list of checked check boxes which you can compare to determine if the checkbox should be checked.
when the form is submitted, populate the list which keeps track of checked items
render the form and compare the list of available checkboxes with checked checkboxes. If item found in both lists, it means that we want to display the checkbox as checked.
index.php
<?php
// Keep this outside of the if statement so the form has access to it.
$availableInterests = [
'fishing',
'camping',
'hiking',
'swimming',
'running',
];
// Keep this outside of the if statement so the form has access to it.
$selectedInterests = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Cast the posted interests to an array in case the user submitted an empty list.
// An empty list would be NULL if we didn't cast it.
$selectedInterests = (array)$_POST['interest'];
// foreach $selectedInterests insert into DB...
// Let this code `fall through` to render the form again.
// $selectedInterests is now populated and can be used in to the form below to keep the selected checkboxes checked.
}
?>
<form method="post">
<!-- Using the `global` $availableInterests array to drive our form. -->
<? foreach ($availableInterests as $interest): ?>
<!-- Do we want to render the checkbox as checked? -->
<?php $checked = (in_array($interest, $selectedInterests)) ? ' checked' : ''; ?>
<input type="checkbox"
name="interest[]"
value="<?php echo $interest; ?>"
<?php echo $checked; ?>>
<?php echo ucfirst($interest); ?>
<?php endforeach; ?>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Let's suppose you have an array of choice list like :
$choices = ["Fishing", "Camping" , "Hiking","Swimming" , "Running" ]
after the user select their choices
$interests = ["Fishing" , "Running" ];
In your case , the coresponding line is :
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
Let's suppose that $newArr is equal to $interests in may example.
foreach ($interests as $interest) {
echo 'you have choose '.$interest.PHP_EOL;
}
As result :
you have choose Fishing
you have choose Running
For not selected :
$notInterests = array_diff($choices,$interests);
foreach ($notInterests as $notInterest) {
echo 'you have not choose '.$notInterest.PHP_EOL;
}
As Result :
you have not choose Camping
you have not choose Hiking
you have not choose Swimming
To handle it in one loop :
foreach ($choices as $choice) {
if(in_array($choice,$interests )){
echo'you have choose '.$choice.PHP_EOL ;
}else{
echo 'you have not choose '.$choice.PHP_EOL;
}
}
Hope this help you.
To help others that might be in a similar situation I would like to post what is now a working solution at least for me based on Mohammed Yassine CHABLI's inspiration. Vantiya who was the first to comment really help me appreciate what was to follow. Thanks guys.
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$choices = $interest->showInterests($userid=19)->choices;
$selected = explode(',', $interests);
$choices = explode(',', $choices);
foreach ($choices as $choice) {
if(in_array($choice,$selected )){
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
checked>'.$choice;
}else{
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
unchecked>'.$choice;
}
}
I have multiple checkboxes within a foreach loop and I need to keep the selected checkboxes checked after the form submission. The code is as below. Please help.
<? $i=0;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
foreach($row=$val)
{
$id="chkbox".$i;
?>
<input type="checkbox" name="chkbx" onclick ="func()" id="<?echo $id;">? value="<?echo $val \n;?>" <? echo "$val";?>
Now where and how to include the checked property of the boxes..
You don't need foreach loop here
This can be done for checking multiple checkbox checked
<?php
$i=0;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
$checked = "";
if($row['database_column_name']=$val){
$checked = "checked";
}
echo '
<input type="checkbox" name="chkbx" onclick ="func()" id="'.$id.'" value="'.$val.'" '.$checked.'>'.
$val
.'
';
}
?>
Works for me.
let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?
What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;
You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)
Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>
I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.
So, I have a couple of check boxes in my $_POST array and I want to see if they are checked or not. Then I would like to print out the ones that are checked. How would I got about doing this?
Usually, the way we play with checkbox is, by using arrayed name like this:
<input type="checkbox" name="check[]" value="check 1" /> check<br />
<input type="checkbox" name="check[]" value="check 2" /> check<br />
<input type="checkbox" name="check[]" value="check 3" /> check<br />
This way, we can easily determine if someone checked our checkbox by using:
if( isset( $_POST['check'] ))
{
if( count( $_POST['check'] ) > 0 )
{
echo "checked value are: " . implode(", ", $_POST['check']);
}
}
This is mainly because browser doesn't send checkbox value that doesn't checked.
You can only print out the checked checkboxes anyway, since the browser wont submit empty (unchecked) checkboxes:
foreach ($_POST as $key=>$val)
{
echo $key ." :: ".$val."<br/>";
}
This expands a little on #iHaveacomputer's answer.
Only checked checkboxes & radios are put into the $_POST or $_GET.
However, you can have an array of checkbox (or other types of input) so if you are using brackets in the names of your inputs, you should check to see if the value is an array or not.
foreach ($_POST as $input_name => $value_s)
{
if (is_array($value_s))
{
foreach ($value_s as $index => $value)
{
echo "$input_name[$index]::$value<br />";
// note that this literally prints the input_name, brackets, and index)
// using braces will just print the value
}
}
else
{
echo "$input_name::$value_s<br />";
}
}
I have a text field and two checkboxes, I need to list users based on the selection. Can anyone show me an example.
See:
Enumerate all Check Box in PHP
<input name="rows[]" value="someVal" type="checkbox" />
<input name="rows[]" value="anotherVal" type="checkbox" />
<?php
// $_POST['rows'] contains the values of all checked checkboxes
//if something has been checked
if(isset($_POST['rows'])) {
//loop over each checked value
foreach ($_POST['rows'] as $row) {
echo $row . '<br />';
}
}
?>
if (isset($_POST['mycheckbox']))
{
draw_selectionCheckboxChecked();
}
else
{
draw_NoCheckbox();
}