1

codes table

id     code
--    ------
1     BB3CA4
2     2788BA
3     E3E3A5
.        .
.        .
.        .

PHP array of 500 semi-unique strings called $codes to be added to the codes table:

$codes = array( 'AC2BE4', 'BC61A2', '34CE5A', ... );

My PDO database connection object:

$dbh = new PDO( "mysql:host=$host;dbname=$db", $user, $pass );

Try 1

Put PDO insert execute within the PHP loop:

foreach( $codes as $code ){
    $stmt = $dbh->prepare("INSERT INTO codes ( code ) VALUES ( :code )");
    $stmt->bindParam( ':code', $code , PDO::PARAM_STR );
    $stmt->execute();
}

I think this is not a good solution!

Try 2

Second try was to construct a long SQL query by gluing 500 SQL queries and run it at once.

1
  • If this is necessary only one time, you can use first code. Commented May 23, 2015 at 15:39

2 Answers 2

3

Prepared statements that do the same query but with different parameters don't have to be created multiple times, just once, so create the statement before the loop, then iterate, you bind the parameters and execute the query inside the loop.

$stmt = $dbh->prepare("INSERT INTO codes ( code ) VALUES ( :code )");
foreach( $codes as $code ){
  $stmt->bindParam( ':code', $code , PDO::PARAM_STR );
  $stmt->execute();
}

With PDO you could even slim the code down a little bit by setting the parameter/s in the execute call:

$stmt = $dbh->prepare('INSERT INTO codes ( code ) VALUES ( :code )');
foreach($codes as $code) {
  $stmt->execute(array('code' => $code));
}
Sign up to request clarification or add additional context in comments.

2 Comments

are multiple executions more efficient than say, imploding multiple groups of brackets of values together, and running them all as a single query?
I'm not sure if its faster, but its safer, cause you get the extra protection from injections that prepared statements gives. And when it comes to 500 inserts, it won't really matter, its fast either way and easier to write with like above in my opinion.
-1
 $sql = "INSERT INTO codes ( code ) VALUES ";
 foreach($codes as $code){        
    $sql = $sql . "($code),"
 }
 $sql = rtrim($sql,",");

I think this is a simple way to insert 500 values at a time into database.

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.