PHP POST 多行到 MySQL
我有一个名为“fruits”的表:
id fruit 1 Apple 1 Banana 2 Apple 2 Apple 2 Pear
我希望能够使用 PHP 一次添加多行。
我尝试使用两组两个文本框(用于 id 和水果),但仅使用最后一组文本框插入 1 行。
编辑:
如果我有这样的表,我该怎么办:
id fruit taste 1 Apple Good 1 Banana Okay 2 Apple Good 2 Apple Bad 2 Pear Good
I have a table named fruits:
id fruit 1 Apple 1 Banana 2 Apple 2 Apple 2 Pear
I would like to be able to add several rows at once using PHP.
I tried having two sets of two textboxes (for id and fruit) but that only insert 1 row, using the last set of textboxes.
EDIT:
Then what do I do if I have a table like this:
id fruit taste 1 Apple Good 1 Banana Okay 2 Apple Good 2 Apple Bad 2 Pear Good
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用括号
[]
正确命名文本框以形成一个数组,然后循环遍历 POST 后的数组以插入数据。确保在使用mysql_real_escape_string
或准备好的查询运行查询之前转义数据。编辑:更新示例,因为OP将信息附加到问题中。
在您提供的扩展示例中,
taste
看起来只有几个选择。在这种情况下,我将在文本框上使用表格
显着变化:使用 PHP 中的简单循环,您可以指定要显示的字段数量,并轻松地将其他选项添加到口味选择框中。我在
[]
中放置了一个任意数字,以确保我们在处理表单时将水果与味道联系起来。处理代码
显着变化:我正在检查以确保水果具有价值,否则它不会插入。我使用该任意值(即数组键
$k
)来选择与水果匹配的口味。You need to name your text boxes properly using brackets
[]
to form an array, then loop through your POST'ed array to insert the data. Be certain you're escaping data before running your query by usingmysql_real_escape_string
or prepared queries.EDIT: Updating examples because OP appended information to the question.
In the extended example you've provided, it looks like the
taste
only has a few choices. In that case, I would use a<select>
element over a text box. Check out my examples for how, personally, I would do it.Form
Notable changes: Using a simple loop in PHP, you can specify the number of fields you want to show and easily add other options to the taste select box. I'm placing an arbitrary number within the
[]
to be certain we link the fruit to the taste when we process the form.Process Code
Notable changes: I'm checking to make sure the fruit has a value, otherwise it won't insert. I'm using that arbitrary value (which is the array key
$k
) to select the taste that matches the fruit.使用内爆功能的单次插入。
你的 HTML
你的 PHP
Single insert using implode function.
Your HTML
Your PHP
MySQL 支持在单个查询中进行多次插入:
MySQL supports multiple inserts in a single query:
您可以创建一个 html 元素数组,例如
在 html
然后在 save.php 中
You can make an html array of elements for example
in html
Then in save.php
在插入语句中只需添加值,如下所示:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
因此,对于您的示例,
插入水果(水果)值('橙色'),('柠檬'),('酸橙');
应该有效。
http://dev.mysql.com/doc/refman/5.5/en /插入.html
In your insert statement just add the values, like so:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
so for your example,
INSERT INTO fruits (fruit) VALUES ('Orange'),('Lemon'),('Lime');
should work.
http://dev.mysql.com/doc/refman/5.5/en/insert.html