Search code examples
phphtmldatabasewebcheckbox

How to check multiple chekbox from database value


I have this code to showing value from database as well as checking the checkbox that have the value :

<?php
    $result = mysqli_query($kon,"SELECT jenis FROM pasien WHERE nopemeriksaan = $nopemeriksaan"); 
    while($row = mysqli_fetch_array($result)) {
        $jenis = explode(",", $row['jenis']);
        print_r($jenis);
?>    
    <input type="checkbox" id="checkup" name="jenis[]" value="checkup" <?php if(in_array("checkup",$jenis)) echo 'checked="checked"'; ?>>
    <label> Check-Up</label><br>
    <input type="checkbox" id="vaksinasi" name="jenis[]" value="vaksinasi" <?php if(in_array("vaksinasi",$jenis)) echo 'checked="checked"'; ?>>
    <label> Vaksinasi</label><br>
    <input type="checkbox" id="usg" name="jenis[]" value="usg" <?php if(in_array("usg",$jenis)) echo 'checked="checked"'; ?>>
    <label"> USG </label><br>
    <input type="checkbox" id="xray" name="jenis[]" value="xray" <?php if(in_array("xray",$jenis)) echo 'checked="checked"'; ?>>
    <label> X-Ray </label><br>
    <input type="checkbox" id="sterilisasi" name="jenis[]" value="sterilisasi" <?php if(in_array("sterilisasi",$jenis)) echo 'checked="checked"'; ?>>
    <label> Sterilisasi</label><br>
    <input type="checkbox" id="operasi" name="jenis[]" value="operasi" <?php if(in_array("operasi",$jenis)) echo 'checked="checked"'; ?>>
    <label> Tindakan Operasi</label><br>
    <input type="checkbox" id="cekdarah" name="jenis[]" value="cekdarah" <?php if(in_array("cekdarah",$jenis)) echo 'checked="checked"'; ?>>
    <label> Cek Darah</label><br>
    <input type="checkbox" id="lainnya" name="jenis[]" value="lainnya" <?php if(in_array("lainnya",$jenis)) echo 'checked="checked"'; ?>>
    <label> Lainnya</label><br>
    
<?php
    }
?>

But however, it always just checking one value even when the array itself has 2 value. Is there anything I write wrong or anything I miss? Thank You very much for your help.


Solution

  • First I'll check if the result returned from the DB is correct by executing the query into the DB (basically validating the SQL) I have doubts that you may need to put $nopemeriksaan in quotes. If everything is looking fine you can check if this part of your code is returning what you expect

    while($row = mysqli_fetch_array($result)) {
            $jenis = explode(",", $row['jenis']);
    

    I used to write PHP and if I remember correctly mysqli_fetch_array is returning an array so in this case instead of using $row['jenis'] you have to use $row[0] If you still want to use the response as a dictionary you can use mysqli_fetch_assoc