Avatar of narmi2
 asked on

Multiple inserts with PDO

Dear Experts,

The following script allows me to insert a single row into the database:

This is because of the array:

array(':column' => $unsafeValue)

Which is a single key:value array.  How can I modify this array so it inserts more than 1 rows into the database in one statement.

Something like this?

array(':column' => $unsafeValue, ':column' => $unsafeValue, ':column' => $unsafeValue, )


Please help.
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $unsafeValue));

Open in new window


Avatar of undefined
Last Comment

8/22/2022 - Mon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

That would still do 1 row with 2 columns.  I would like to know if it is possible to use the same technique, but with a modified array and insert into multiple rows.

narmi2 -> look more carefully.

the SQL would insert two rows.

hello narmi2, I can not see a way to have multiple inserts with a single statement like -
$stmt->execute(array(':column' => $unsafeValue, ':column' => $unsafeValue));

but this works for me -

$cal = 'Mixed Up';
$addy = 'www.experts.com';
$mail = 'way\'s to, go';

$stmt = $dbo->prepare('INSERT INTO games (addy) VALUES (:addy)');
$stmt->bindParam(':addy', $val,PDO::PARAM_STR);
$aAry = array($addy, $mail, $cal);
foreach($aAry as $val) $stmt->execute();
// will insert three rows with different values in each row

however to expand this to have more than one column added for each row would need more stuff,
as far as I can tell you will need some sort of for loop that does a separate  $stmt->execute();  for each row inserted
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck