简体   繁体   中英

How to set checkboxes into 'checked' based from the values in database?

I want to make an "Edit" feature for my patients record. One of the requirement is to check checkboxes. I use this code to insert it in the database

<div class="col-xs-12 col-sm-6">
   <input type="checkbox" value="Sulfa drugs" name="Allergic[]">  
   <label>Sulfa drugs</label> 

   <input type="checkbox" value="Aspirin" name="Allergic[]">                 
   <label>Aspirin</label>  

   <input type="checkbox" value="Latex" name="Allergic[]">&nbsp;                 
   <label>Latex</label> 
</div>

<?php
   $Allergic = implode(', ', ($_GET['Allergic']));
      $sql = "INSERT INTO history_table (allergic) VALUES ('$Allergic')";
?>

This code is working successfully. The data were inserted if it's checked; as a string in one column only.

column allergic -> Aspirin, Latex

When the user clicked the edit button, the checkboxes that has been checked must be filled/checked.

I tried this code but it only works if it has one checked only, if its multiple, nothing happens

<input type="checkbox" value="Aspirin" name="Allergic[]" 
<?php echo ($row['allergic']=='Aspirin')?'checked':'' ?>>

<input type="checkbox" value="Latex" name="Allergic[]" 
<?php echo ($row['allergic']=='Latex')?'checked':'' ?>>

Hope someone can help me I've been working on this for almost a day. Thank you!

Please read up on cleaning your inputs, prepared statements, and at the very least the basics of securing your code against SQL Injection attacks. As it stands now, anyone with knowledge of your website URL could gain full control of your entire database with a few lines of code.

That being said, the question you have is easily solved:

in_array('Aspirin', explode(", ", $row['allergic'])) ? 'checked' : '';

just put your logic within a tag and then echo 'checked' based on your logic see the code below

<input type="checkbox" style="width: 20px; height: 20px;"  
class="checkme" name="checkme[]" 
id="checkme_'.$sub_sub_gap_row['sub_sub_gap_id'].'" 
value="'.$sub_sub_gap_row['sub_sub_gap_id'].'"';?>
<?php if(isset($_GET['sub_sub_gap_id'])){
$selected_topic_id = $_GET['sub_sub_gap_id'];
if($selected_topic_id == $sub_sub_gap_row['sub_sub_gap_id'])
{
echo 'checked';
}
}
?>
<?php
echo  '>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM