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();
}
我尝试了很多方法,但只返回空值或“Array”字符串。我的观点是让这些值(value)变成这个
INSERT INTO table (id, kind, qty) VALUES (1, v2, v3), (1, v2.1, v3.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 注入(inject)的准备......
关于php - 如何将此数据插入mysql php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32268455/