0

我有这样的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>

当我选择多个选项时,我的数据库中只有一个值。例如,我选择自行车和电机。数据库中只有电机

4

2 回答 2

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 变量放入数据库之前对其进行清理。

于 2013-08-20T16:32:12.807 回答
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']);
于 2013-08-20T16:32:20.547 回答