Display array from php using html form checkbox - php

I have a form of checkboxes as shown below:
<form method="POST" action="display.php">
<input type="checkbox" value="1" name="options[]">
<span class="checkboxText"> Fruits</span>
<input type="checkbox" value="2" name="options[]">
<span class="checkboxText">Vegetables </span><br><br>
<button class="button" type="submit" value="display">DISPLAY</button>
</form>
I get the options[] using $_POST['options'] and save the array of data in a variable. I want to display the array of fruits if the fruits checkbox is checked, the vegetables array if vegetables checkbox is checked and display both of them if both are checked and display a message saying "Fruits and Vegetables are healthy". This is the php code I have so far but it does not seem to work as I would like it to.
<?php
$values = $_POST['options'];
$n = count($values);
for($i=0; $i < $n; $i++ )
{
if($values[$i] === "1" && $values[$i] == "2")
{
//iteration to display both tables
echo 'Fruits and Vegetables are healthy';
}
else if($values[$i] === "1")
{
//display fruits
}
else if( $values[$i] == "2")
{
//display vegetables
}
}
?>
The problem with my php code is that is does not go into the first if at all. It just displays both tables from the other two ifs (since the echo is not displayed either). Is there any way I could solve this?

You shouldn't need a loop for this. You just need to check in $_POST['options'] for each of the values in question. I would suggest using the text you want to display as the values for your checkboxes so you don't have to convert from numbers to words.
<input type="checkbox" value="Fruits" name="options[]">
<span class="checkboxText"> Fruits</span>
<input type="checkbox" value="Vegetables" name="options[]">
<span class="checkboxText">Vegetables </span><br><br>
Then for the display, just output the fruits/vegetables arrays depending on whether or not those values are present in $_POST['options'].
if (!empty($_POST['options'])) {
echo implode(' and ', $_POST['options']) . " are healthy";
if (in_array('Fruits', $_POST['options'])) {
// show the fruits
}
if (in_array('Vegetables', $_POST['options'])) {
// show the veg
}
}

Related

How to display checked check boxes together with non-checked ones

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;
}
}

Checking all checkboxes are checked using PHP

I have few checkboxes, I want to find whether all the checkboxes are checked and if yes return a message.
<label class="control-label col-md-3">L4 Deliverables</label>
<?php
while($subd_row=$subd_result->fetch_assoc()){
if($sub_row['selected'] == 1)
{
?>
<input class="flat" type="checkbox" name="L4d[]" value="<?php echo $subd_row['d_name'];?>" checked><?php echo $subd_row['d_name'];?></input>
}
Using the above code the checkboxes are displayed. The message could be for example: " 14 checkboxes are checked".
You can use $i to increment when it goes in that if statement it will increment,
<label class="control-label col-md-3">L4 Deliverables</label>
<?php $i = 0;
while ($subd_row = $subd_result->fetch_assoc()) {
if ($sub_row['selected'] == 1) {
$i++;
?>
<input class="flat" type="checkbox" name="L4d[]" value="<?php echo $subd_row['d_name']; ?>" checked><?php echo $subd_row['d_name']; ?></input>
<?php
}
}
?>
<label><?php echo ($i <= 1 ? "$i checkbox is ": "$i checkboxes are ")."checked"; ?></label>
On the backend, you can always check the length of the variables/array passed by a form.
L4d[] will have the values of checked checkboxes only.
You can simply check as:
if(count($_POST['L4d']))== 14) {...}
If you want something like an alert box to be popped up when all the checkboxes are checked, then you may call a javascript function 'onChange' of your checkbox field

PHP : Turn checked checkboxes into list of items for database table and check boxes based on values stored in database table on page load

I am storing content into a database table. One table column is called attrbutes and has a list of values such as (ex: 1, 3, 5) based on the checkboxes that were checked.
<form>
<input type="checkbox" name="attribute" value="1">Attr 1<br>
<input type="checkbox" name="attribute" value="2">Attr 2<br>
<input type="checkbox" name="attribute" value="3">Attr 3<br>
<input type="checkbox" name="attribute" value="4">Attr 4<br>
<input type="checkbox" name="attribute" value="5">Attr 5<br>
<form>
Couple of questions on how to integrate checkboxes with PHP...
1) How do I check to see if at least 1 checkbox is checked on form submit?
2) How do I turn the checked checkboxes into a list like 1, 3, 5 if checkboxes 1, 3, and 5 are selected.
3) As a reverse to #2, on page load I need to figure out how to check each checkbox that's value is listed in the database column. if 1, 3, 5 is listed in table column, I need checkboxes 1 3 and 5 checked on page load.
I know how to code the basic queries for inserting, updating, and removing etc...but I've never worked with checkboxes and storing values from checkboxes using php before.
Change you html:
<input type="checkbox" name="attribute[]" value="1">Attr 1<br>
<input type="checkbox" name="attribute[]" value="2">Attr 2<br>
<input type="checkbox" name="attribute[]" value="3">Attr 3<br>
<input type="checkbox" name="attribute[]" value="4">Attr 4<br>
<input type="checkbox" name="attribute[]" value="5">Attr 5<br>
1)
$checkedAttr = $_POST['attribute'];
if(count($checkedAttr) > 0)
echo "At least one checkbox is selected";
2)
$checkboxList = implode(',', $checkedAttr);
3)
$checkedAttr = explode(',', $yourQueryResultStringContainingTheCheckedList);
<input type="checkbox" name="attribute[]" value="1" <?php if(in_array('1', $checkedAttr)) echo 'checked=\"checked\"'; ?>Attr 1<br>
...
1, 2) You can treat form elements as arrays with name="attribute[]" then loop through the posted values in your php as an array.
For example:
<?php
$attributes = $_POST['attribute'];
if(empty($attributes)) {
echo "No attributes selected";
} else {
// echo whole array
print_r($attributes);
// loop through array
foreach($attributes as $attribute) {
echo $attribute." ";
}
// create list as one whole string
$list = implode(',', $attributes);
}
?>
3) When you are building the form (using php) you can check each value in a loop. Note that I also made your labels proper labels so they will also activate the checkbox if clicked.
<?php
// need some code to get db values into array
$attributes = array(1,3,5); // your list
// loop through the amount of checkboxes you want
for($i=1; $i <= 5; $i++) {
if(in_array($i, $attributs) { // check for a match with current checkbox
$checked = " checked";
} else {
$checked = "";
}
echo'<input type="checkbox" name="attribute[]" id="attribute'.$i.'" value="'.$i.'"'.$checked.'><label for="attribute'.$i.'">Attr 1</label><br>'
}
?>

Getting values of HTML checkboxes in php

I am creating an HTML form and I have a textbox in that. My requirement is that a user can check multiple check boxes, and then I have to get all checked values and then send the values to the database (I want to use PHP).
Here is my code for within the textbox
$Intensive=$_POST['Intensive'];
$Intensive_count=count($Intensive);
$i=0;
//$count=0;
//$index;
$max=0;
//$index;
While($i < $Intensive_count)
{
if($Intensive[$i]=="High frequency ventilation" )
{
$Intensive_score=4;
}
elseif($Intensive[$i]=="Mechanical ventilation with muscle relaxation")
{
$Intensive_score=4;
}
elseif($Intensive[$i]=="Mechanical ventilation")
{
$Intensive_score=3;
}
elseif($Intensive[$i]=="CPAP")
{
$Intensive_score=2;
}
elseif($Intensive[$i]=="supplemental oxygen")
{
$Intensive_score=1;
}
if($Intensive_score>$max)
{
$max=$Intensive_score;
$index=$i;
}
$i++;
}
Now with the above code I am able to echo the value ,but the record is not going to the database.
$sql1="insert into Form2 values('$Medical_Record_Id','$sub1','$Question1','4','$Intensive[$index]','$max')";
mysql_query($sql1);
Could anybody tell me how to go about it.
Thanks ..:)
Assuming you are using POST as the method for sending the form those checkboxes are in, you can get the values array with $_POST['Intensive'].
I would recommend you use integers for the value instead of long strings, also an ID is supposed to be unique, so modify your ids.
HTML:
<input type="checkbox" name="Intensive[]" id="r1" value="1">supplemental oxygen<br>
<input type="checkbox" name="Intensive[]" id ="r2" value="2">supplemental oxygen<br>
<input type="checkbox" name="Intensive[]" id="r3" value="3">Mechanical ventilation<br>
<input type="checkbox" name="Intensive[]" id="r4" value="4">Mechanical ventilation with muscle relaxation<br>
<input type="checkbox" name="Intensive[]" id="r5" value="5">High-frequency ventilation
PHP:
foreach($_POST['Intensive'] as $data) {// Or $_GET
if ($data == 1){
/// do so and so
}
if ($data == 2){
/// do so and so
}
... and so on.
}

How to list users based on checkbox selection?

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();
}

Categories