简体   繁体   中英

Insert 500 rows to MySQL from PHP array

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.

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));
}
 $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM