doulu7174 2016-01-21 23:16
浏览 39
已采纳

这个简单的代码Checkbox从PHP到MYSQL的数组有什么问题?

I am not sure what I am missing with this Array output of php to mysql. It really seems simple and I am missing something. I would think it would break it up into checkbox[1], checkbox[2], checkbox[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();
?> 
  • 写回答

1条回答 默认 最新

  • dozc58418381 2016-01-21 23:22
    关注

    Only checked checkboxes are successful controls.

    So if no checkbox is checked, then the array will be empty.

    If one is checked, then it will have one item in it (at index 0 not index 1, arrays start counting from 0).


    In general, this should be resolved with a many-to-many relationship.

    After inserting your data (without checkboxes) into your "table" table, loop over $_POST['checkboxitems'] and insert the id of your new row and the id of the matching foodstuff in the "foodstuffs" table into your linking table.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵