如果复选框的值已经在mysql中,如何显示复选框?

时间:2017-02-16 09:30:35

标签: javascript php jquery html5 css3

代码:

<?php
 if(isset($_POST['save']))
  { 
    $checkbox1=$_POST['company_name'];  
    $chk=implode(',',$checkbox1);

    $sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
    $value = mysqli_query($link,$sql);
    if($value == true)
    {
        $msg .="<h5 style='color:green'>Successfull</h5>";
    }
    else
    {
        $msg .="<h5 style='color:red'>Error!</h5>";
    }
  }
?>

<?php
    extract($_POST);
    $sql = mysqli_query($link,"select * from placement order by company_name  ASC");
    while ($row = mysqli_fetch_array($sql)) 
        {
            echo "<li>
                    <input type='checkbox' name='company_name[]' id='company_name' value=".$row['image_name'].">&nbsp; ".$row['company_name']."<br/>
                </li>";
        }
?>

如果字符串已经在像image1,image2,image3这样的mysql数据库中,我想检查复选框。那么,我该怎么办呢?请帮忙

谢谢

2 个答案:

答案 0 :(得分:2)

检查while循环并在条件满足时分配选中的值。如下面的代码所示。

while ($row = mysqli_fetch_array($sql)) 
{      
$isCheked = "";
 if($row['isCheked']) {//test if the values is checked in the db
  $isCheked = "checked";
 }
 echo "<li><input type='checkbox' ".$isCheked." name='company_name[]' id='company_name' value=".$row['image_name'].">&nbsp; ".$row['company_name']."<br/></li>";
 }

答案 1 :(得分:0)

尝试这样。使用ternary operator(:?)检查名称是否已设置。

 while ($row = mysqli_fetch_array($sql)) 
        {
            $name = $row['image_name'];
            $check = isset($name)?"checked":"";

            echo "<li>
                    <input type='checkbox' name='company_name[]' id='company_name' value='".$name."'".$check." >&nbsp; ".$row['company_name']."<br/>
                </li>";
        }