我有一个html页面,其中有一个表单,并将结果保存到MySQL中。问题是,复选框只在MySQL表上保存一个值。为了在db列中保存多个值,我必须做什么?
HTML代码:
<input type="checkbox" name="rating[]" value="Homepage">Homepage
<input type="checkbox" name="rating[]" value="Facilities">Facilities
<input type="checkbox" name="rating[]" value="reservation">Reservation
<input type="checkbox" name="rating[]" value="Contact">Contact
PHP代码:
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO db (firstname, lastname, password, email, address, postcode, country, phonenumber, rating, subscribe)
VALUES ('$firstname', '$lastname', '$password', '$email', '$address', '$postcode','$country', '$phonenumber', '$rating', '$subscribe')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo " Success!";
我认为您有三种选择。
首先。
创建另一个表并用外键连接它们。
第二。
使复选框具有值并执行位掩码。
Ex)
<input type="checkbox" name="something[]" value="1">blah
<input type="checkbox" name="something[]" value="2">blah2
<input type="checkbox" name="something[]" value="4">blah3
如果有人勾选"blah"answers"blah3",则将其设为5。(1&4)
像这样:
for($i=0; $i<count($rating); $i++)
{
$rating_value &= $rating[$i];
}
并以整数形式保存到数据库中。
第三。
将它们连接到一个字符串中,并将其保存到字符串中的数据库中(如VARCHAR)。
如果$rating
是一个数组,请尝试内爆()
$sql="INSERT INTO db (firstname, lastname, password, email, address, postcode, country, phonenumber, rating, subscribe)
VALUES ('$firstname', '$lastname', '$password', '$email', '$address', '$postcode','$country', '$phonenumber', '".implode(',',$rating)."', '$subscribe')";
我强烈建议您阅读以下内容:
- 如何循环数组
- 如何使用准备好的报表
但是您还没有PHP或HTML问题。你试图将信息存储在一个没有位置的数据库中。
你至少需要两张额外的桌子:
-
带有的
rating
主表rating_id
(自动递增或任意代码)rating_value
(例如"较差"、"一般"、"良好"…)
存储可用评级的位置。
-
带有的
db_rating
表格db_id
(db
的主键)rating_id
(rating
的主键)
存储关系的位置。
并删除您当前的db.rating
列。