-3
$dbh = new PDO($dsn, $username, $password);

$query = 'INSERT INTO `table1` (`id`, `name`) VALUES (?, ?)';
$values = [
    [1, 'Mary'],
    [2, 'Peter'],
    [3, 'Mike']
];

$stmt = $dbh->prepare($query);
$stmt->execute($values);

I know the above codes will cause errors. But if I want to INSERT multiple records with placeholders conveniently, how can I do?

Benson
  • 115
  • 1
  • 7
  • 6
    Possible duplicate of [PDO Prepared Inserts multiple rows in single query](https://stackoverflow.com/questions/1176352/pdo-prepared-inserts-multiple-rows-in-single-query) – CBroe Aug 15 '17 at 08:17
  • OK, thank you very much! It seems that there aren't "elegant" ways to achieve this. – Benson Aug 15 '17 at 08:39
  • 1
    There is not really a need for one ... with prepared statements, statement and data are send to the database independently from each other. So you can bind parameters and then execute the statement in a loop; this does not slow things down as sending a “traditional” statement for individual row inserts multiple times would. – CBroe Aug 15 '17 at 08:42
  • Thank you for your helpful instructions! – Benson Aug 15 '17 at 10:41

1 Answers1

0

@CBroe has provided good answers for this question. Please refer to the above comments, and especially refer to the link that he posted, which has more detailed discussions within it.

Benson
  • 115
  • 1
  • 7