PHP :将选中的复选框转换为数据库表的项目列表,并根据页面加载时存储在数据库表中的值来复选框



我正在将内容存储到数据库表中。 一个表列称为 attrbutes,它有一个值列表,例如 (例如:1, 3, 5 ),基于选中的复选框。

<form>
<input type="checkbox" name="attribute" value="1">Attr 1<br>
<input type="checkbox" name="attribute" value="2">Attr 2<br>
<input type="checkbox" name="attribute" value="3">Attr 3<br>
<input type="checkbox" name="attribute" value="4">Attr 4<br>
<input type="checkbox" name="attribute" value="5">Attr 5<br>
<form>

关于如何将复选框与 PHP 集成的几个问题...

1) 如何检查表单提交时是否至少选中了 1 个复选框?

2)如果选中了复选框1,3和5,如何将选中的复选框转换为类似1, 3, 5的列表。

3)作为#2的反转,在页面加载时,我需要弄清楚如何检查数据库列中列出的每个复选框的值。如果1, 3, 5列列在表列中,我需要在页面加载时选中复选框 1 3 和 5。

我知道如何编写用于插入、更新和删除等的基本查询......但我以前从未使用过复选框并使用 php 存储复选框中的值。

更改你的 html:

<input type="checkbox" name="attribute[]" value="1">Attr 1<br>
<input type="checkbox" name="attribute[]" value="2">Attr 2<br>
<input type="checkbox" name="attribute[]" value="3">Attr 3<br>
<input type="checkbox" name="attribute[]" value="4">Attr 4<br>
<input type="checkbox" name="attribute[]" value="5">Attr 5<br>

1)

$checkedAttr = $_POST['attribute'];
if(count($checkedAttr) > 0)
    echo "At least one checkbox is selected";

2)

$checkboxList = implode(',', $checkedAttr);

3)

$checkedAttr = explode(',', $yourQueryResultStringContainingTheCheckedList);
<input type="checkbox" name="attribute[]" value="1" <?php if(in_array('1', $checkedAttr)) echo 'checked="checked"'; ?>Attr 1<br>
...

1, 2) 您可以使用 name="attribute[]" 将表单元素视为数组,然后将 php 中发布的值作为数组循环。

例如:

<?php
$attributes = $_POST['attribute'];
if(empty($attributes)) {
  echo "No attributes selected";
} else {
  // echo whole array
  print_r($attributes);
  // loop through array
  foreach($attributes as $attribute) {
    echo $attribute." ";
  }
  // create list as one whole string
  $list = implode(',', $attributes);
}
?>

3)当你构建表单(使用php)时,你可以在循环中检查每个值。 请注意,我还为您的标签制作了正确的标签,以便它们在单击时也会激活复选框。

<?php
// need some code to get db values into array
$attributes = array(1,3,5); // your list
// loop through the amount of checkboxes you want
for($i=1; $i <= 5; $i++) {
    if(in_array($i, $attributs) { // check for a match with current checkbox
      $checked = " checked";
    } else {
      $checked = "";
    }
  echo'<input type="checkbox" name="attribute[]" id="attribute'.$i.'" value="'.$i.'"'.$checked.'><label for="attribute'.$i.'">Attr 1</label><br>'
}
?>

最新更新