Skip to content

Instantly share code, notes, and snippets.

@lbp0200
Created March 16, 2015 08:35
Show Gist options
  • Save lbp0200/1580144b6f1af7db1363 to your computer and use it in GitHub Desktop.
Save lbp0200/1580144b6f1af7db1363 to your computer and use it in GitHub Desktop.
php mysql multiple insert
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=mytest', 'root', '123', array(
PDO::ATTR_PERSISTENT => true));
$rows = array(
array(null, 'def', time()),
array(null, 'def', time()),
array(null, 'def', time()),
array(null, 'def', time()),
array(null, 'def', time()),
);
for ($i = 0; $i < 10000; $i++) {
array_push($rows, array(null, 'def', time()));
}
$t1 = microtime(true);
$args = array_fill(0, count($rows) * count($rows[0]), '?');
$params = array();
$query = "INSERT INTO ntable (id, name, ntime) VALUES ";
foreach ($rows as $row) {
$query .= "(?,?,?),";
foreach ($row as $value) {
$params[] = $value;
}
}
$query = substr($query, 0, -1);
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$r = $stmt->execute($params);
$t2 = microtime(true);
echo (($t2 - $t1) * 1000) . 'ms';
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//result 380.75590133667ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment