13
你好,我正在做一個類,在pdo中做多重插入。PDO MySQL:在一個查詢中插入多行
它是這樣的
INSERT INTO $table (key1,key2,key3,etc) VALUE (value1,value2,value3,etc), (value1,value2,value3,etc), (value1,value2,value3,etc)
搜索,我發現,我要建立類似
INSERT INTO $table (key1,key2,key3,etc) VALUE (:key1,:key2,:key3,etc), (:key1,:key2,:key3,etc), (:key1,:key2,:key3,etc)
然後用這個$this->execute($data);
其中$data
是
0 =>
array
'key1' => 'value1'
'key2' => 'value2'
'key3' => 'value3'
1 =>
array
'key1' => 'value1'
'key2' => 'value2'
'key3' => 'value3'
etc
執行後
問題是我仍然得到一個錯誤Array to string conversion
$insert->execute($data);
我該如何解決這個問題?
這是我正在做的一個片段。
public function multipleInsert($table, $data = array())
{
# INSERT (name) VALUE (value),(value)
if (count($data) > 1)
{
$fieldnames = array_keys($data[0]);
$count_inserts = count(array_values($data));
$count_values = count(array_values($data[0]));
# array(????) untill x from first data
for($i = 0; $i < $count_values; $i++)
{
$placeholder[] = '?';
}
# array((????),(????),(????)) for query
for ($i=0; $i < $count_inserts; $i++)
{
$placeholders[] = '('. implode(',',$placeholder) . ')';
}
$query = 'INSERT INTO '. $table;
$query .= '(`'. implode('`, `', $fieldnames) .'`)';
$query .= ' VALUES '. implode(', ', $placeholders);
$insert = $this->start->prepare($query);
$i = 1;
foreach($data as $item)
{
foreach ($item as $key => $value)
{
$insert->bindParam($i++, $item[$key]);
}
}
echo $query;
$insert->execute();
$return['status'] = true;
$return['lastid'] = $this->start->lastInsertId();
return $return;
}
else
{
die('$data is less then two array, use single insert instead.');
}
}
那麼它執行了4次?即時通訊尋找一種方式來插入多個數據在一個單一的查詢,通過查看您的代碼執行多次取決於多少數據。 – 2012-04-08 06:01:45
@AdamRamadhan,正如我告訴你的,這是避免併發症的一種方法。稍後我會用合併的更新。 – Starx 2012-04-08 06:07:12
@AdamRamadhan,檢查更新 – Starx 2012-04-08 06:21:26