Array
(
[id] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[kind] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[qty] => Array
(
[0] => 123
[1] => 456
[2] => 789
)
)
这就是我的数据的样子。这是我的插入1行代码
function insert($table, $array_data)
{
$key = array();
$value = array();
foreach($array_data as $v=>$row){
$key[] = $v;
$value[] = "'".$row."'";
}
$data_key = implode(',', $key);
$data_value = implode(',', $value);
$sql = "INSERT INTO ".$table."(".$data_key.") VALUES (".$data_value.")";
$this->setQuery($sql);
$this->query();
}
请帮我创建一个插入多行的功能,比如
function insert_multi($table, $array_data)
{
...
$sql = "INSERT INTO ".$table."(".$data_key.") VALUES (".$data_value1."), (".$data_value2.")";
$this->setQuery($sql);
$this->query();
}
我尝试了许多方法,但只返回空值或"数组"串。我的观点是让这些价值变成这个
INSERT INTO table (id, kind, qty) VALUES (1, v2, v3), (1, v2.1, v3.1),...
非常感谢! ^^
答案 0 :(得分:1)
function insert_multi($table, $array_data)
{
$sql = "INSERT INTO " . $table . " (" . implode(',', array_keys($array_data)) . ") VALUES ";
$rows = [];
$columns = array_keys($array_data);
for ($ii = 0; $ii < count($array_data[$columns[0]]); $ii++) {
$values = [];
foreach ($columns as $column) {
$values [] = $array_data[$column][$ii];
}
$rows [] = "('" . implode("','", $values) . "')";
}
$sql .= implode(',', $rows);
$this->setQuery($sql);
$this->query();
}
但是在以这种方式构建查询时支持自己进行SQL注入...
答案 1 :(得分:0)
希望这会对你有所帮助。未经测试,如果有任何语法错误,请进行更改。 你需要生成一个像(val1,val2),(val3,val3)
这样的字符串function them($table, $array_data)
{
...
$keys = array_keys($array_data);
$length = count($array_data[$keys[0]]);
$sql = '';
for ($i=0;$i < $length;$i++)
{
$sql .= "('";
foreach($keys as $index => $key){
$sql .= $array_data[$key][$i];
if($index < count($keys)-1)
$sql .= ",";
}
$sql .= "')";
// if there is another array member, add a comma
if( $i < $length-1 )
{
$sql .= ",";
}
}
$sql = "INSERT INTO ".$table."(".implode(',',$keys).") VALUES ".$sql;
$this->setQuery($sql);
$this->query();
}