从多选列表(html表单)向mysql数据库插入数据 [英] insert data to mysql database from multiple select list (html form)
问题描述
我制作了一个表格,其中有商店的 ID:
I make a form, where there is ID of a shop:
<input type="text" name="shopId">
还有一个多选选择:
<select name="cars" multiple required>
在我选择选项后,我必须将它们传递给数据库中的一个表;表包含 2 列:shopId 和 car.问题是它只传递一个选项,不可能像在一家商店的两个或三个模型中那样将几行添加到表格中.我想我必须像数组或其他东西一样传递数据.请你帮帮我好吗.
after i get selected options, i have to pass them to a table in the database; table consists of 2 columns: shopId and car. The thing is it passes only one option and it is impossible to have a few rows added to the table like in one shop two or three models. I suppose i have to pass the data like an array or something. Can you help me, please.
$shopId = $_GET["shopId"];
$cars = $_GET["cars"];
这是一个查询:
$query = "INSERT INTO shops (shopId, car) VALUES ($shopId, $cars)";
推荐答案
我想说,鉴于约束,您唯一的选择是将所有选定的选项组合成一个逗号分隔的字符串(使用 PHP 的内置函数称为 implode http://php.net/implode),然后插入 shopID 和逗号分隔的列表汽车进入一个新的行.我会这样做:
I'd say given the constraints, the only option you have is to combine all the selected options into a single comma separated string (using PHP's built-in function called implode http://php.net/implode), then insert the shopID and the comma-separated-list of cars into a new row. I'd do it like this:
<?php
if ($_POST) {
$cars_string = implode(', ', $_POST['cars']);
$sql = '
INSERT INTO
`my_table` (
`shopID`,
`cars`
)
VALUES (
'. $_POST['shopID'] .',
"'. $cars_string .'"
)
';
mysql_query($sql) OR die(mysql_error());
}
?>
<form method="post" action="">
Shop ID: <input type="text" name="shopID"/> -
<select name="cars[]" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<input type="submit" name="Submit"/>
</form>
这是最好的解决方案考虑到您提供的限制.但是,我没有看到每个表单提交只能添加一行的逻辑.这不是一个好的数据库设计,尤其是从长远来看.
This is the best solution given the constraints you've provided. However, I do not see the logic in only being able to add a single row per form submit. That is not a good database design, especially in the long-term.
请注意 元素如何具有
name="cars[]"
名称,并密切注意后面的开/关方括号字 cars[]
.这将允许通过表单传递多个选项,而不是只有一个.正如@bart2puck 在他的解决方案中提到的,这是一个关键的区别,不应被忽视.此外,允许用户选择多个选项的对浏览器最友好的方式是在 元素中使用属性
multiple="multiple"
.
Please notice how the <select>
element has the name of name="cars[]"
and pay close attention to the open/close square brackets after the word cars[]
. This will allow multiple options to be passed through the form, instead of only one. This is a critical difference and it should not be overlooked, as @bart2puck mentions in his solution. Also, the most browser-friendly way to allow users to select multiple options is to use the attribute multiple="multiple"
in your <select>
element.
这篇关于从多选列表(html表单)向mysql数据库插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!