PHP批量插入foreach

puk*_*978 4 php mysql

我有一个 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,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") . "')");
}
Run Code Online (Sandbox Code Playgroud)

然而,正如我想象的那样,该脚本的插入速度非常慢,因为它编写了每个单独的记录。count 变量是为每个页面返回的记录数,而 page 变量是一个简单的页面计数器。

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

提前致谢。

mag*_*tik 5

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

$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);
Run Code Online (Sandbox Code Playgroud)