如果值与数据库中的值相同,则选中Checked in Checkbox

时间:2012-10-09 05:10:41

标签: php

如果复选框中的值与数据库中的值相同,我尝试在复选框中添加选中:

My database :
Column = skin_type 
Value = Normal, Dry, Oily

My Default html checkbox :
<input type="checkbox" name="skin_type[]" value="Normal">Normal &nbsp;
<input type="checkbox" name="skin_type[]" value="Dry">Dry &nbsp;
<input type="checkbox" name="skin_type[]" value="Oily">Oily &nbsp;
<input type="checkbox" name="skin_type[]" value="Combination">Combination &nbsp;
<input type="checkbox" name="skin_type[]" value="Sensitive">Sensitive

因此,如果值为Normal, Dry, Oily,则会选中此值的复选框,例如下面的

enter image description here

下面是我当前的php脚本(我首先尝试爆炸数据但不确定如果值与数据库中的值相等,如何添加检查):

<?php 
$query_skin_type = mysql_query("SELECT skin_type FROM `customers` WHERE customers_id='".$_GET['cID']."'");
while($info = mysql_fetch_array($query_skin_type)) {

$skin_type = explode(", ", $info['skin_type']);

    foreach ($skin_type as $value) {
    $value.'<br>';
    }
}
?>

4 个答案:

答案 0 :(得分:1)

您可以编写一个小函数来检查$ skin_type数组。例如:

$skin_type = explode(", ", $info['skin_type']);

function isChecked($val, $arr){
  if(in_array($val, $arr)){
    echo 'checked';
  }
}

<input type="checkbox" name="skin_type[]" value="Normal" checked="<?php isChecked('Normal', $skin_type); ?>">Normal &nbsp;
//etc...

请注意,我会以完全不同的方式生成标记,但这样就足够了,不需要任何重构。

答案 1 :(得分:0)

<input type="checkbox" name="skin_type[]" value="Normal" 
<?php
foreach ($skin_type as $value) {
if($value == "Normal") { echo "checked='checked'"; }
}
?> >Normal &nbsp;

<input type="checkbox" name="skin_type[]" value="Dry" <?php
foreach ($skin_type as $value) {
if($value == "Dry") { echo "checked='checked'"; }
}
?> >Dry &nbsp;

<input type="checkbox" name="skin_type[]" value="Oily"  
<?php
foreach ($skin_type as $value) {
if($value == "Oily") { echo "checked='checked'"; }
}
?> 
>Oily &nbsp;

<input type="checkbox" name="skin_type[]" value="Combination"  
<?php
foreach ($skin_type as $value) {
if($value == "Combination") { echo "checked='checked'"; }
}
?> 
>Combination &nbsp;

<input type="checkbox" name="skin_type[]" value="Sensitive"  <?php
foreach ($skin_type as $value) {
if($value == "Sensitive") { echo "checked='checked'"; }
}
?> 
>Sensitive

答案 2 :(得分:0)

$skin_type = explode(", ", $info['skin_type']);


<input type="checkbox" name="skin_type[]" value="Normal" <?php if(in_array("Normal",$skin_type)){ ?>?checked="checked" <?php } ?>>Normal &nbsp;

答案 3 :(得分:0)

选中复选框取决于数据库值

'<input type="checkbox" class="checkbox" name="s_info[]" id="'.$ccid.'-S-'.$value['receipt_no'].'" value="'.$ccid.'-S-'.$value['receipt_no'].'" '. ($value['verified']? "checked":"") .'/>'.