勾选多个复选框后,我会在屏幕上打印阵列


after ticking more than one checkbox i get array printed on screen

我使用论坛建立了一个复选框组,一切都在创建的独立脚本上运行,但是当我将其添加到我的用户系统后选择多个时,我得到了数组回显,列表应该在下面是生产脚本

<?php
session_start();
include 'dbconfig.php';
$chkbox = array('option1', 'option2', 'option3');
if (isset($_POST['submit']))
{
 $chkbox = $_POST['chkbox'];
 $chkNew = "";  
 foreach($chkbox as $chkNew1)  
   {  
      $chkNew .= $chkNew1 . ",";  
   }  

 $query = "INSERT INTO demo_table_5 (MultipleValue) VALUES ('$chkNew')";
 mysqli_query($conn,$query) or die(mysqli_error());
  }
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Insert/Store multiple selected checkbox values in MySQL database</title>
</head>
<body>
<h2>PHP Insert multiple checkbox values in MySQL database</h2>
 <form method="post" action="">
 <table>
 <tr>
 <td><input type="checkbox" name="chkbox[]" value="option1"><label>option1</label></td>
 <td><input type="checkbox" name="chkbox[]" value="option2"><label>option2</label></td>
 <td><input type="checkbox" name="chkbox[]" value="option3"><label>option3</label></td>
 </tr>
 <tr>
 <td colspan="4"><input type="submit" name="submit" Value="submit"></td>
 </tr>
 </table>
 </form>
<?php
$sql = "SELECT MultipleValue FROM demo_table_5";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
    echo "<table><tr><th>Interests</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["MultipleValue"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?> 
</body>
</html>

所以当我把它添加到脚本中时,我把

 <table>
 <tr>
 <td><input type="checkbox" name="chkbox[]" value="option1"><label>option1</label></td>
 <td><input type="checkbox" name="chkbox[]" value="option2"><label>option2</label></td>
 <td><input type="checkbox" name="chkbox[]" value="option3"><label>option3</label></td>
 </tr>

在寄存器形式中 它自己

然后我把以下内容放在注册页面顶部的 php 块中

$chkbox = array('option1', 'option2', 'option3');

我在数据库中的现有userinfo表中添加了一列,并将其命名为multiValue,并添加了以下行来更新数据库

MultipleValue       = '".$_POST['chkbox']."',

然后我将以下位添加到个人资料页面

<?php
$sql = "SELECT MultipleValue FROM user_info";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Interests</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["MultipleValue"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

由于您的输入具有name="chkbox[]",这意味着$_POST['chkbox']是一个包含所有复选框值的数组。在 PHP 中,当您尝试将数组用作字符串时,如

MultipleValue       = '".$_POST['chkbox']."',

数组将转换为字符串"Array"。您需要使用 implode 将其转换为逗号分隔的列表:

MultipleValue       = '".implode(',', $_POST['chkbox'])."',

但是,我建议您更改表格设计。表格单元格中的逗号分隔值是表示列表的不良方式,因为很难搜索和更新它们 - 例如,索引不能用于搜索列表中的单个值。应使用多对多表,其中每个用户+选项组合都有一行。

您在数据库中插入了一个串联的字符串,例如"选项1,选项2,选项3"。

通过 SQL select 语句检索数据将返回一行包含串联