加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP批量插入foreach

发布时间:2020-12-13 16:45:20 所属栏目:PHP教程 来源:网络整理
导读:我有一个curl脚本,它从远程源读取数据.以下是当前代码: function download_page($path){ $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$path); curl_setopt($ch,CURLOPT_FAILONERROR,1); curl_setopt($ch,CURLOPT_FOLLOWLOCATION,CURLOPT_RETURNTRANSFE
我有一个curl脚本,它从远程源读取数据.以下是当前代码:

function download_page($path){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$path);
    curl_setopt($ch,CURLOPT_FAILONERROR,1);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,CURLOPT_RETURNTRANSFER,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变量是每页返回的记录数,页变量是简单的页计数器.

我想知道是否有办法进行批量插入语句一次插入所有100条记录.

提前致谢.

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读