我已经使用论坛构建了一个复选框组,所有内容都在创建的独立脚本上工作,但当我将其添加到我的用户系统后,选择多个我得到的数组回显到列表应该在下面的是生产脚本
<?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表中添加了一列,并将其命名为multipleValue,并添加了以下行来更新数据库
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();
?>
答案 0 :(得分:2)
由于您的输入为name="chkbox[]"
,这意味着$_POST['chkbox']
是一个包含所有复选框值的数组。在PHP中,当您尝试将数组用作字符串时,如
MultipleValue = '".$_POST['chkbox']."',
数组转换为字符串"Array"
。您需要使用implode
将其转换为以逗号分隔的列表:
MultipleValue = '".implode(',', $_POST['chkbox'])."',
但是,我建议您更改表格设计。表格单元格中以逗号分隔的值是表示列表的不好方法,因为搜索和更新它们很困难 - 例如,索引不能用于搜索列表中的各个值。您应该使用多对多表,其中每个用户+选项组合都有一行。
答案 1 :(得分:0)
您在数据库中插入了一个连接字符串,例如“option1,option2,option3”。
通过SQL select语句检索数据将返回包含串联
的一行