how to get checkbox value from database in php for

2019-08-09 03:30发布

问题:

in database values are stored as "A,B,C,D,E,F" etc. now i have to fetch those data in the form for update. i have to check the checkbox if it matches the value with database value.

i am doing this kind of code(which i know is wrong)

    <input type="checkbox" name="time[]" value="free" <?php if(!strpos($row['best'], 'free')=="false") { echo "checked='checked'";} ?> />Free
    <input type="checkbox" name="time[]" value="Open" <?php if(!strpos($row['best'], 'Open')=="false") { echo "checked='checked'"; }?>/>Open Source
    <input type="checkbox" name="time[]" value="portable" <?php if(!strpos($row['best'], 'portable')=="false") { echo "checked='checked'"; }  ?> />Portable
    <input type="checkbox" name="time[]" value="support" <?php if(!strpos($row['best'], 'support')=="false") {
                        echo "checked='checked'"; }?> />Support

回答1:

When strpos is 0 (first character), then it is equal to false if you use double = (==). You need to use ===false. Besides it should be false, not "false".



回答2:

You can do in this way:

suppose you have four static values : <

?php
$time = ['free', 'open' , 'portable', 'support']; // your checkboxes
$fromDb = explode(',', $row['best']);
foreach($time as $t):
?>
<input type="checkbox" name="time[]" value="<?php echo $t;?>" <?php if(in_array($t, $fromDb) { echo "checked='checked'";} ?> /><?php echo ucfirst($t);?>
<?php endforeach;?>