我有这样的PHP代码:
<?php
if(isset($_POST['submit']))
{
if(!empty($_POST['vehicles']))
{
$vehicles=$_POST['vehicles'];
$hostname='localhost';
$username='root';
$password='root';
$dbname='pet';
$connect=mysqli_connect($hostname,$username,$password,$dbname) or die("can't connect to server");
$query="UPDATE information SET transportation='$vehicles'";
$query=mysqli_query($connect,$query) or die("can't execute query");
echo "inserted";
}
else
{
echo "error";
}
}
else
{
echo "choose your vehicle";
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Select transportation you have</title>
</head>
<body><h2>Select transportation you have</h2>
<form action="#" method="POST">
<input type="checkbox" name="vehicles" value="bike"/>I have bike<br/>
<input type="checkbox" name="vehicles" value="car"/>I have car<br/>
<input type="checkbox" name="vehicles" value="motor"/>I have motor<br/>
<input type="submit" name="submit" value="submit"/>
</form>
</html>
当我选择多个选项时,我的数据库中只有一个值。例如我选择自行车和电机。数据库中只有电机
答案 0 :(得分:0)
通过在名称末尾添加[]来将输入的名称更改为数组
<input type="checkbox" name="vehicles[]" value="bike"/>I have bike<br/>
<input type="checkbox" name="vehicles[]" value="car"/>I have car<br/>
<input type="checkbox" name="vehicles[]" value="motor"/>I have motor<br/>
然后在php中,您将能够使用数组语法访问它们,您只需使用implode
制作逗号分隔的车辆列表。
$_POST['vehicles'][0]
$_POST['vehicles'][1]
$_POST['vehicles'][2]
//etc...
$vehicles = implode(",",$_POST['vheicles']);
$query="UPDATE information SET transportation='$vehicles'";
//$query would contain something like:
//UPDATE information SET transportation='bike,car'
当然,在将它们放入数据库之前对POST变量进行卫生处理。
答案 1 :(得分:0)
您需要将html更改为:
<input type="checkbox" name="vehicles[]" value="bike"/>I have bike<br/>
<input type="checkbox" name="vehicles[]" value="car"/>I have car<br/>
<input type="checkbox" name="vehicles[]" value="motor"/>I have motor<br/>
将PHP更改为:
$vehicles=implode(',',$_POST['vehicles']);