显示mysql中所有已选中复选框的值,并将其显示在表中

时间:2016-05-04 09:22:11

标签: php mysql checkbox

我设计了用户注册页面。它有一个野外爱好。我在复选框的帮助下设计了该字段。如果用户选择了两个或更多爱好,我将爱好ID保存在数据库中。现在我需要显示特定用户在其个人资料编辑页面中选择的所有爱好名称。我完成了下面的编码,但它显示了数据库中没有选中的复选框名称。应检查用户选择的复选框名称。但它没有那样做。请提供任何帮助。

<?php
$query = "SELECT * FROM hobbies";
$result = mysqli_query($con, "$query");
while ($r=mysqli_fetch_array($result)){
    $hobbyid=$r["hobby_id"];
    $hobbyname=$r["hobby_name"]; 
    if($hobby==$r[0]){ //Here $hobby is the hobby id which is entered by the user when registration. That hobby id is saved in the db.
        echo "<input type='checkbox' checked name='check_list[]' value='echo $hobbyid;'> $hobbyname";   
    }else{
        echo "<input type='checkbox' name='check_list[]' value='echo $hobbyid;'> $hobbyname";
    }
}
?>

2 个答案:

答案 0 :(得分:0)

Try again with below code segment. I have modified your code.
<?php
$query = "SELECT * FROM hobbies";
$result = mysqli_query($con, "$query");

while ($r=mysqli_fetch_array($result)) {
    $hobbyid = $r["hobby_id"];
    $hobbyname = $r["hobby_name"]; 

    $isChecked = '';
    if($hobby == $r["hobby_id"]) { //Here $hobby is the hobby id which is entered by the user when registration. That hobby id is saved in the db.
        $isChecked = "checked='checked'";
    }

    echo "<input type='checkbox' $isChecked checked name='check_list[]' value='$hobbyid;'/> $hobbyname";   
}
?>

答案 1 :(得分:0)

我尝试了以下编码,它给出了我想要的结果。

<?php
  $query = "SELECT * FROM hobbies";
$flag=false;
$result = mysqli_query($con, "$query");

while ($r=mysqli_fetch_array($result)) 
{
$hobbyid = $r["hobby_id"];
$hobbyname = $r["hobby_name"];
$hob_id=explode(',',$hobby);
$size = sizeof($hob_id);
for($i=0;$i<$size;$i++) 
{ 
  if($hob_id[$i]==$hobbyid) 
  {
    $flag=true;
  } 
}
if($flag==true) 
{
      ?>
  <input  type='checkbox' name='check_list[]' value="<?php echo $r['hobby_id']; ?>" checked  > <?php echo $r['hobby_name']; ?> <br>
  <?php
  $flag=false;
} 
else 
{ 
  ?>
  <input  type='checkbox' name='check_list[]' value="<?php echo $r['hobby_id']; ?>"> <?php echo $r['hobby_name']; ?> <br>
  <?php
}
}
?>