PHP批量插入foreach [英] PHP bulk insert foreach

查看:122
本文介绍了PHP批量插入foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个curl脚本,可以从远程源读取数据.下面是当前代码:

I have a curl script which reads the data from a remote source. Below is the current code:

function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);                      
    curl_close($ch);
    return $retValue;
}
$sXML = download_page('http://remotepage.php&function=getItems&count=100&page=1');
$oXML = new SimpleXMLElement($sXML);
foreach($oXML->results->item->item as $oEntry){
    $insert_query = mysql_query("INSERT INTO tbl_item (first_name, last_name, date_added) VALUES ('" . $oEntry->firstname . "', '" . $oEntry->lastname . "', '" . date("Y-m-d H:i:s") . "')");
}

但是脚本的插入速度非常慢,因为我想像它是因为它写入了每条记录. count变量是每页返回多少记录,而page变量是简单的页面计数器.

The script works however is extremely slow to insert as I imagine its because its writing each individual record. The count variable is how many records returned for each page and the page variable is a simple page counter.

我想知道是否有一种方法可以执行批量插入语句一次插入所有100条记录.

I am wondering if there is a way to do a bulk insert statement to insert all 100 records at once.

提前谢谢.

推荐答案

您可以在一个语句中执行以下操作:

You can do this within one statement by doing something like this :

$sXML = download_page('http://remotepage.php&function=getItems&count=100&page=1');
$oXML = new SimpleXMLElement($sXML);
$query = "INSERT INTO tbl_item (first_name, last_name, date_added) VALUES";
foreach($oXML->results->item->item as $oEntry){
    $query .=  "('" . $oEntry->firstname . "', '" . $oEntry->lastname . "', '" . date("Y-m-d H:i:s") . "'),";
}
mysql_query($query);

这篇关于PHP批量插入foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆