Php 重写代码以使用PDO并提高多个插入的效率
我有以下代码,我希望能够更有效地执行数据库中的插入,并更新代码以使用PDO:Php 重写代码以使用PDO并提高多个插入的效率,php,mysql,loops,insert,pdo,Php,Mysql,Loops,Insert,Pdo,我有以下代码,我希望能够更有效地执行数据库中的插入,并更新代码以使用PDO: foreach ($urls as $i => $url) { //path to csv file $web = "http://path-to-file/".$url; $ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); curl_setopt($ch, C
foreach ($urls as $i => $url) {
//path to csv file
$web = "http://path-to-file/".$url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt ($ch, CURLOPT_URL, $web);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
//explode the csv file by new line
$r = explode("\n", $result);
$sql = "insert into product (`product_name`) values ";
for ($i = 1; $i <= count($r); $i++){
//explode each row by comma
$n = explode(",", $r[$i]);
$product_name = $n[0];
$sql .= "('$product_name'),";
}
$sql = trim($sql, ",");
if(count($n) != 0)
mysql_query($sql);
}
foreach($url作为$i=>$url){
//csv文件的路径
$web=”http://path-to-file/“$url;
$ch=curl_init();
curl_setopt($ch,CURLOPT_COOKIEJAR,“cookies.txt”);
curl_setopt($ch,CURLOPT_COOKIEFILE,“cookies.txt”);
curl_setopt($ch,CURLOPT_URL,$web);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_超时,30);
$result=curl\u exec($ch);
//按新行分解csv文件
$r=分解(“\n”,$result);
$sql=“插入到产品(`product\U name`)值中”;
对于($i=1;$i),使用最简单的代码执行此操作:
// Start PDO connection (DataBaseHandler)
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $password);
// Prepare a reusable insert statement and bind the variable
$insert = $dbh->prepare("INSERT INTO product (`product_name`) VALUES (:product_name)");
$insert->bindParam(':product_name',$product_name);
// Use foreach for arrays
foreach($r as $row){
//explode each row by comma
$n = explode(",", $row);
$product_name = $n[0];
// Execute the prepared INSERT statement referring to the current product name
$insert->execute();
}
不确定在一条语句中执行######插入是否比执行###单独的插入语句更快,但由于使用了PDO准备的语句,此代码肯定更简单、更高效:
编辑:
根据,执行一个大查询要快得多。我希望我让您开始使用PDO和准备好的语句,但这样做会让您学到最好的东西,我将让您自己创建新的PDO查询。这可能会让您开始:对不起,这不是询问Stackoverflow问题的方式。您为什么不尝试阅读一些在线教程和自己编写代码?