sam orten
sam orten

Reputation: 206

how to show checkbox checked if value of checkbox is already in mysql?

code:

<?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>";
        }
?>

Here I want to checked checkbox if the string is already in mysql database like image1,image2,image3. So, How can I do this ? please help

Thank You

Upvotes: 0

Views: 83

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

Check in your while loop and assign the checked value if condition is satisfied. Like shown in below code.

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>";
 }

Upvotes: 2

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

Try like this.Use ternary operator(:?) for checking whether the name is set or not.

 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>";
        }

Upvotes: 0

Related Questions