使用PDO预准备语句插入多值
在一个execute语句中插入多个值。为什么这样,因为根据此页面,它比常规插入更快。
$datafields = array('fielda', 'fieldb', ... );$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);更多的数据值,或者您可能有一个循环来填充数据。
使用准备好的插入,您需要知道要插入的字段以及创建?的字段数。占位符以绑定您的参数。
insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
基本上,这就是我们希望插入语句看起来的样子。
现在,代码:
function placeholders($text, $count=0, $separator=","){ $result = array(); if($count > 0){ for($x=0; $x<$count; $x++){ $result[] = $text; } } return implode($separator, $result);}$pdo->beginTransaction(); // also helps speed up your inserts.$insert_values = array();foreach($data as $d){ $question_marks[] = '(' . placeholders('?', sizeof($d)) . ')'; $insert_values = array_merge($insert_values, array_values($d));}$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " . implode(',', $question_marks);$stmt = $pdo->prepare ($sql);try { $stmt->execute($insert_values);} catch (PDOException $e){ echo $e->getMessage();}$pdo->commit();尽管在我的测试中,使用多个刀片和具有单个值的常规预加工刀片仅相差1秒。



