我对此很陌生,如果这是一个非常简单的问题,请对不起。当我尝试使用多选项html表单插入mysql时,它只会插入从下拉列表中选择的最后一个选项,但是会多次插入该选项。
HTML
<form action ="test_page.php" method="post">
<select name= fruit[] size="8" multiple>
<option value ="Apples" >Apples</option>
<option value ="Oranges" >Oranges</option>
<option value ="Bananas" >Bananas</option>
<option value ="Grapes" > Grapes </option>
<option value ="Strawberries"> Strawberries</option>
</select>
<br><br>
<input type="submit" name="submit" value="Submit" />
</form>`
这是PHP
<?php
foreach ($_POST["fruit"] as $favourite)
{
$sql = "INSERT INTO Fruit_table (Apples, Oranges, Bananas, Grapes) VALUES ('$favourite','$favourite','$favourite', '$favourite');";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
答案 0 :(得分:-1)
我发现了您的问题!
因此,实际上您只在执行最后一个时才使用$sql
多次设置foreach
。
像这样;
foreach ($_POST["fruit"] as $favourite)
{
$sql = "INSERT INTO Fruit_table (Apples, Oranges, Bananas, Grapes)
VALUES ('$favourite','$favourite','$favourite', '$favourite');";
}
这是完整的有效代码!
<?php
foreach ($_POST["fruit"] as $favourite)
{
$sql = "INSERT INTO Fruit_table (Apples, Oranges, Bananas, Grapes)
VALUES ('$favourite','$favourite','$favourite', '$favourite');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
所以,我只更改了foreach()
的位置。现在应该可以使用!
答案 1 :(得分:-2)
在名称周围加上引号。
从此:
<select name=fruit[] size="8" multiple>
对此:
<select name="fruit[]" size="8" multiple>