简体   繁体   English

从PHP数组向MySQL插入500行

[英]Insert 500 rows to MySQL from PHP array

codes table codes

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

PHP array of 500 semi-unique strings called $codes to be added to the codes table: 将500个半唯一字符串的PHP数组(称为$codes添加到codes表中:

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

My PDO database connection object: 我的PDO数据库连接对象:

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

Try 1 尝试1

Put PDO insert execute within the PHP loop: 将PDO插入执行放在PHP循环中:

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 试试2

Second try was to construct a long SQL query by gluing 500 SQL queries and run it at once. 第二种尝试是通过粘合500个SQL查询并立即运行它来构造一个长SQL查询。

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: 使用PDO您甚至可以通过在execute调用中设置参数来使代码变小一点:

$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. 我认为这是一次将500个值插入数据库的简单方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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