Mysql 是否在一列中插入多个值?
我有一个复选框和值表,如果用户选中复选框,为了简单起见,他们会在一个名为checkedHW的数组中选择id的值,这就是代码的样子:Mysql 是否在一列中插入多个值?,mysql,Mysql,我有一个复选框和值表,如果用户选中复选框,为了简单起见,他们会在一个名为checkedHW的数组中选择id的值,这就是代码的样子: $ids = implode(',',arrayofids); $sql = "insert into table(id, type) values($ids,type); $db->query($sql); 用于测试的回显查询: "insert into table('id1,id2','type') 我想如果我循环这个查询,我可以假设这样做: "in
$ids = implode(',',arrayofids);
$sql = "insert into table(id, type) values($ids,type);
$db->query($sql);
用于测试的回显查询:
"insert into table('id1,id2','type')
我想如果我循环这个查询,我可以假设这样做:
"insert into table('id1','type');"
"insert into table('id2','type');"
但我不太清楚该怎么做,任何帮助都会很好:)
我实际上是通过以下方法解决的:
for($i=0;$i<count(arrayofids); $i++){
$sql = "insert into table(id,type) values(array[$i], 'type'";
$db->query($sql);}
for($i=0;$iquery($sql);}
我希望这能帮助别人,并感谢你们的帮助!两个查询完全不同
插入表('id1,id2','type')
将插入单行
id1,id2 |型
鉴于
insert into table('id1','type');"
insert into table('id2','type');"
将插入两行
id1|类型id2 |型
因此,如果您的id列是
int
类型,那么您不能运行第一次查询如果您有一系列复选框,并且希望将值插入表中,您可以像这样循环:
<?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";
$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";
$db->query($query);
希望能有所帮助。您可以这样做:
<?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";
$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";
$db->query($query);
这是将要提交的内容:
INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
在表(id,type)中插入值(1,'type'),(2,'type'),(3,'type'),(4,'type')我认为
id
dataType是int。我刚刚添加了一个int cast,它只为第一个值插入一行。我能够在不使用内爆的情况下解决它,但感谢您的帮助!