如何在PHP中执行多个MySQL插入 [英] How to perform multiple MySQL inserts in PHP
本文介绍了如何在PHP中执行多个MySQL插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在MySQL表中插入许多行(介于150到300之间),并且我想在性能方面更好地了解以下方法:
I need to insert many rows ( between 150 to 300 ) into MySQL table and I want to know the better of the following approaches in terms of performance:
方法1:
foreach( $persons as $person ){
$stmt = $dbLink->prepare( "INSERT INTO table SET id = :ID,
name = :name,
email = :email,
mobile = :mobile");
$stmt->execute( array( ':ID'=>$person->getID(),
':name'=>$person->getName(),
':email'=>$person->getEmail(),
':mobile'=>$person->getMobile(),
) );
}
方法2:
$stmt = $dbLink->prepare( "INSERT INTO table SET id = :ID,
name = :name,
email = :email,
mobile = :mobile");
$stmt->bindParam( ':ID', $person->getID(), PDO::PARAM_STR );
$stmt->bindParam( ':name', $person->getName(), PDO::PARAM_STR );
$stmt->bindParam( ':email', $person->getEmail(), PDO::PARAM_STR );
$stmt->bindParam( ':mobile', $person->getMobile(), PDO::PARAM_STR );
foreach( $persons as $person ){
$stmt->execute();
}
推荐答案
不同之处在于对数据库的调用数量.尽可能减少通话量.
It is the amount of calls to the database what makes the difference. Reduce the amount of calls as much as possible.
代替此:
insert (a,b,c) values (d,e,f);
insert (a,b,c) values (g,h,i);
insert (a,b,c) values (j,k,l);
insert (a,b,c) values (m,n,o);
执行以下操作:
insert (a,b,c) values (d,e,f),(g,h,i),(j,k,l),(m,n,o);
因此,一次通话就可以完成4次通话.
Thus making in one call what you would do in 4 calls.
这篇关于如何在PHP中执行多个MySQL插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文