2

I have a php array. I want to insert all of them into a column in mysql table using PDO.

$myArray = array("12397", "45263426", "253725372","2735724372");
$sql = "DROP TEMPORARY TABLE IF EXISTS T_Temp;
        CREATE TEMPORARY TABLE T_Temp (
        AccountID varchar(120)
      );";

Now I want to insert all the array values into T_Temp table in single shot. I don't want to use foreach.

6
  • I don't want to use foreach...why would that matter? Just use whatever works. Commented Aug 23, 2021 at 15:17
  • What have you tried so far? Where are you stuck? Commented Aug 23, 2021 at 15:31
  • I have a lot of data. foreach might take a lot of time. It would be great if there is any other way to achieve it. Commented Aug 23, 2021 at 15:57
  • "foreach might take a lot of time" - why should it? Such a loop is fast, and if you need something more performant, better import the data directly into the database, without using PHP Commented Aug 23, 2021 at 15:59
  • I will do the performance testing between 'foreach' and solution from Bill Karwin. Commented Aug 23, 2021 at 21:12

2 Answers 2

1

Here's a solution that does not use foreach:

<?php

$myArray = array("12397", "45263426", "253725372","2735724372");
$sql = "DROP TEMPORARY TABLE IF EXISTS T_Temp;
        CREATE TEMPORARY TABLE T_Temp (
        AccountID varchar(120)
      );";

$pdo = new PDO('mysql:dbname=test;host=127.0.0.1', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec($sql);

$placeholders = implode(",", array_fill(1, count($myArray), "(?)"));
$insertSql = "INSERT INTO T_Temp (AccountID) VALUES {$placeholders}";

$pdo->prepare($insertSql)->execute($myArray);
Sign up to request clarification or add additional context in comments.

Comments

0

to insert multiple values at once you can write this kind of query

INSERT INTO table_name (column_list)
VALUES
    (value_list_1),
    (value_list_2),
    ...
    (value_list_n);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.