Ankit Bhatanagar
Ankit Bhatanagar

Reputation: 37

Add Checked in Checkbox if same value in database

I try to add checked in my checkbox, if a value in checkbox is same with the value from database:

My database : Column = fees_month[] Value = '$row[month]'

My Default checkbox :
echo "<th >"."<input type='checkbox' name='fees_month[]' value= '$row[month]' checked='isChecked('$row[month]',$fees_month)' >". $row['month']."</th>";

$q = mysqli_query($conn,"SELECT * FROM fees WHERE registration_number='$qry[registration_number]'");

while ($info = mysqli_fetch_array($q)) {
    $fees_month = explode(", ", $info['fees_month']);
}

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

Upvotes: 0

Views: 342

Answers (3)

Danila Ganchar
Danila Ganchar

Reputation: 11222

$selected = array();
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'user', 'password');

$query = $pdo->prepare('
    SELECT fees_month 
      FROM fees 
     WHERE registration_number = :registration_number
');

$query->bindParam('registration_number', $qry[registration_number]);

while ($row = $query->fetch()) {
    $selected[] = $row['fees_month'];
}

$checked = in_array($active, $selected) ? 'checked="checked"' : '';
echo '<input type="checkbox" name="fees_month[]" ' . $checked . ' value="' . $active . '"/>';

// example for testing
$active = 1;
$selected = array(1, 10, 20);
$checked = in_array($active, $selected) ? 'checked="checked"' : '';

echo '<input type="checkbox" name="fees_month[]" ' . $checked . ' value="' . $active . '"/>';

Upvotes: 1

gegham-ayvazyan
gegham-ayvazyan

Reputation: 41

Html checkbox sends value "on" on submitting if checked. If you are directly saving the submitted value, than you should check if the value is on.

For example variable $checkbox stores the value that you retrieved from database, you can use something like this :

<?php $isChecked = $checkbox == 'on' ? 'checked="checked"' : '';
echo "<input type='checkbox' $isChecked>";
?>

Upvotes: 0

heiglandreas
heiglandreas

Reputation: 3861

isChecked is not a variable so variable substitution doesn't work here.

You'll have to do something like the following:

'" . isChecked(<params>) . "'

instead.

Upvotes: 0

Related Questions