MySQL 在mysql的一列中插入多个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12430587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert multiple values in one column mysql?
提问by bubbles
I have a table of checkboxes and values, if a user selects a checkbox they select the value of the id in an array called checkedHW for simplicity sake this is what code looks like:
我有一个复选框和值表,如果用户选择一个复选框,为了简单起见,他们会在一个名为 checkedHW 的数组中选择 id 的值,代码如下所示:
$ids = implode(',',arrayofids);
$sql = "insert into table(id, type) values($ids,type);
$db->query($sql);
echo query for testing:
用于测试的回显查询:
"insert into table('id1,id2','type')
I figured that if I loop through this query I could hypothetically do this:
我想,如果我遍历这个查询,我可以假设这样做:
"insert into table('id1','type');"
"insert into table('id2','type');"
but I'm not exactly quite sure how to do, any help would be wonderful :)
但我不太确定该怎么做,任何帮助都会很棒:)
I actually solved it using:
我实际上使用以下方法解决了它:
for($i=0;$i<count(arrayofids); $i++){
$sql = "insert into table(id,type) values(array[$i], 'type'";
$db->query($sql);}
I hope that helps someone and thank you guys for the help!
我希望对某人有所帮助,并感谢你们的帮助!
回答by Kermit
You could do something like this:
你可以这样做:
$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";
$db->query($query);
This is what would be getting submitted:
这是将要提交的内容:
INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
回答by diEcho
Both query are completely different
两个查询完全不同
insert into table('id1,id2','type')
will insert single row
insert into table('id1,id2','type')
将插入单行
id1,id2 | type
id1,id2 | 类型
whereas
然而
insert into table('id1','type');"
insert into table('id2','type');"
will insert two rows
将插入两行
id1 | type
id2 | type
id1 | 输入
id2 | 类型
so if your idcolumn is int
type then you cant run first query
所以如果你的id列是int
type 那么你不能运行第一个查询
回答by Martin Bean
If you have a series of checkboxes, and wanting to insert the values into your table, you could loop through them like this:
如果您有一系列复选框,并且想要将值插入到您的表中,您可以像这样循环遍历它们:
<?php
$values = array();
foreach ($_POST['field_name'] as $i => $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
$sql = "INSERT INTO `table_name` (`column_name`) VALUES $values";
This will give you a SQL query similar to:
这将为您提供类似于以下内容的 SQL 查询:
INSERT INTO `table_name` (`column_name`) VALUES (1),(2),(3),(4)
Hope this help.
希望这有帮助。