这个简单的代码有什么问题 从PHP到MYSQL的数组复选框


What is wrong with this simple code Checkbox to array from PHP to MYSQL?

我不确定这个 php 到 mysql 的数组输出缺少什么。 这看起来真的很简单,我错过了一些东西。 我认为它会将其分解为复选框[1],复选框[2],复选框[3]。

<html>
<body>
<form method="post" action="output_to_sql.php">
Check box - Please choose type of residence:<br />
Steak:<input type="checkbox" value="Steak" name="checkbox[]"><br />
Pizza:<input type="checkbox" value="Pizza" name="checkbox[]"><br />
Chicken:<input type="checkbox" value="Chicken" name="checkbox[]"><br />
<input type="submit" value="submit" name="submit">
</form>

output_to_sql.php

<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo "success";
}
$checkbox = $_POST["checkbox"];
if (!isset($_POST['submit'])) { 
// if page is not submitted to itself echo the form
echo "error submitting form";
} 
else //show form data with check box answers
{
//make an array with check boxes and show result
foreach ($checkbox as $checkboxitems) {
echo $checkboxitems."<br />";
}
$sql =  mysqli_query("INSERT INTO `table` (`checkbox1`, `checkbox2`, `checkbox3`) VALUES ('$checkboxitems[0]','$checkboxitems[1]','$checkboxitems[2]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?> 

只有选中的复选框才是成功的控件。

因此,如果未选中复选框,则数组将为空。

如果选中一个,那么它将包含一个项目(在索引 0 而不是索引 1 处,数组从 0 开始计数)。


通常,这应该通过多对多关系来解决。

将数据(不带复选框)插入"表"表后,循环遍历$_POST['checkboxitems']并将新行的 id 和"foods"表中匹配食品的 id 插入到链接表中。