我已经使用论坛构建了一个复选框组,所有东西都可以在创建的独立脚本上工作,但是当我将它添加到我的用户系统后,选择多个,我就会得到数组的回显,列表应该在下面是生产脚本。
<?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();
?>
发布于 2016-03-18 19:19:22
由于输入有name="chkbox[]"
,这意味着$_POST['chkbox']
是一个数组,包含所有复选框的值。在PHP中,当您尝试将数组用作字符串时,如
MultipleValue = '".$_POST['chkbox']."',
数组被转换为字符串"Array"
。您需要使用implode
将其转换为逗号分隔的列表:
MultipleValue = '".implode(',', $_POST['chkbox'])."',
但是,我建议您更改表的设计。表单元格中以逗号分隔的值是表示列表的糟糕方法,因为很难搜索和更新它们--例如,索引不能用于搜索列表中的单个值。您应该使用一个多到多的表,其中每个user+option组合都有一行。
发布于 2016-03-18 19:04:27
在db中插入一个连接字符串,如"option1,option2,option3“。
通过SQL select语句检索数据将返回一行,其中包含连接。
https://stackoverflow.com/questions/36092329
复制相似问题