一尘不染

在PHP PDO MYSQL中插入多行的最佳方法是什么?

mysql

假设我们要在表格中插入多行:

$rows = [(1,2,3), (4,5,6), (7,8,9) ... ] //[ array of values ];

使用PDO:

$sql = "insert into `table_name` (col1, col2, col3) values (?, ?, ?)" ;

现在,您应该如何继续插入行?像这样?

$stmt = $db->prepare($sql);

foreach($rows as $row){
  $stmt->execute($row);
}

还是像这样?

$sql = "insert into `table_name` (col1, col2, col3) values ";
$sql .= //not sure the best way to concatenate all the values, use implode?
$db->prepare($sql)->execute();

哪种方法更快更安全?插入多行的最佳方法是什么?


阅读 368

收藏
2020-05-17

共1个答案

一尘不染

您至少有以下两个选择:

$rows = [(1,2,3), (4,5,6), (7,8,9) ... ];

$sql = "insert into `table_name` (col1, col2, col3) values (?,?,?)";

$stmt = $db->prepare($sql);

foreach($rows as $row)
{
    $stmt->execute($row);
}

OR:

$rows = [(1,2,3), (4,5,6), (7,8,9) ... ];

$sql = "insert into `table_name` (col1, col2, col3) values ";

$paramArray = array();

$sqlArray = array();

foreach($rows as $row)
{
    $sqlArray[] = '(' . implode(',', array_fill(0, count($row), '?')) . ')';

    foreach($row as $element)
    {
        $paramArray[] = $element;
    }
}

// $sqlArray will look like: ["(?,?,?)", "(?,?,?)", ... ]

// Your $paramArray will basically be a flattened version of $rows.

$sql .= implode(',', $sqlArray);

$stmt = $db->prepare($sql);

$stmt->execute($paramArray);

如您所见,第一个版本具有许多简单的代码;但是第二个版本确实执行了批量插入。批处理插入应该更快,但是我同意 @BillKarwin的观点
,在绝大多数实现中性能差异不会被注意到。

2020-05-17