Bạn có thể xây dựng tuyên bố sẵn sàng sử dụng mã như đã đề cập ở đây,
PDO Prepared Inserts multiple rows in single query
PHP logic sẽ được loại giống như,
/**
* Insert With Ignore duplicates in Mysql DB.
*
* @param string $date Date.
*/
public static function insertWithIgnore($em, $container, $tableName, $fields, $rows)
{
$query = "INSERT IGNORE INTO $tableName (`" . implode('`,`', $fields) . "`) VALUES ";
$placeHolr = array_fill(0, count($fields), "?");
$qPart = array_fill(0, count($rows), "(" . implode(',', $placeHolr) . ")");
$query .= implode(",", $qPart);
$pdo = self::getPDOFromEm($em, $container);
$stmt = $pdo->prepare($query);
$i = 1;
foreach ($rows as $row) {
$row['created_at'] = date("Y-m-d H:i:s");
foreach ($fields as $f) {
if (!isset($row[$f])) {
$row[$f] = null;
}
$stmt->bindValue($i++, $row[$f]);
}
}
$result = $stmt->execute();
if ($result == false) {
$str = print_r($stmt->errorInfo(), true);
throw new \Exception($str);
}
$stmt->closeCursor();
$pdo = null;
}
/**
* Replace old rows in Mysql DB.
*
* @param string $date Date.
*/
public static function replace($em, $container, $tableName, $fields, $rows, $extraFieldValues = null)
{
if ($extraFieldValues != null) {
$fields = array_unique(array_merge($fields, array_keys($extraFieldValues)));
}
$query = "REPLACE INTO $tableName (`" . implode('`,`', $fields) . "`) VALUES ";
$placeHolr = array_fill(0, count($fields), "?");
$qPart = array_fill(0, count($rows), "(" . implode(',', $placeHolr) . ")");
$query .= implode(",", $qPart);
$pdo = self::getPDOFromEm($em, $container);
$stmt = $pdo->prepare($query);
$i = 1;
foreach ($rows as $row) {
if ($extraFieldValues != null) {
$row = array_merge($row, $extraFieldValues);
}
foreach ($fields as $f) {
$stmt->bindValue($i++, $row[$f]);
}
}
$stmt->execute();
if (!$stmt) {
throw new \Exception("PDO::errorInfo():" . print_r($stmt->errorInfo(), true));
}
$stmt->closeCursor();
$pdo = null;
}
Ví dụ bạn có một số cố định của các thông số, do đó, nó đã giải quyết. Bạn có thể giải quyết vấn đề của mình thêm một chút không? Bạn đã thử những gì cho đến nay? Về cơ bản nó sẽ hoạt động giống nhau nhưng thêm nhiều thông số hơn, ví dụ: trong vòng lặp 'foreach'. – hakre
Bạn có thể tạo câu lệnh chuẩn bị bằng cách sử dụng mã như được đề cập ở đây, http://stackoverflow.com/questions/1176352/pdo-prepared-inserts-multiple-rows-in-single-query –