【问题标题】:Add Checked in Checkbox if same value in database如果数据库中的值相同,则添加 Checked in Checkbox
【发布时间】:2015-11-08 20:52:24
【问题描述】:

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

我的数据库: 列 = fee_month[] 值 = '$row[月]'

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

【问题讨论】:

  • @danila,你有什么建议我错了吗?
  • $q = mysqli_query($conn,"SELECT fee_month FROM Fees WHERE registration_number='$qry[registration_number]'"); while($info = mysqli_fetch_array($q)) { $fees_month = explode(",", $info['fees_month']);函数 isChecked($val, $arr) { if(in_array($val,$arr)) { echo 'checked'; } } } echo "".""。 $row['month']."";

标签: php mysql checkbox mysqli


【解决方案1】:
$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 . '"/>';

【讨论】:

  • 它不工作,只打印了几次没有空格。
【解决方案2】:

isChecked 不是变量,因此变量替换在这里不起作用。

您必须执行以下操作:

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

相反。

【讨论】:

  • 使用提供的代码@danila-ganchar。这是我的解决方案,无需您为自己做点什么。
【解决方案3】:

如果选中,Html 复选框会在提交时发送值“on”。如果您是直接保存提交的值,则应检查该值是否打开。

例如变量$checkbox存储你从数据库中检索的值,你可以使用这样的东西:

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

【讨论】:

  • 您能提供更多信息吗?您如何保存信息(如果已选中)?
猜你喜欢
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多