我有一個捲曲腳本從遠程源讀取數據。下面是當前的代碼:PHP批量插入foreach
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變量是每個頁面返回多少條記錄,頁面變量是一個簡單的頁面計數器。
我想知道是否有辦法做到一次插入所有100條記錄的批量插入語句。
在此先感謝。
$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);
http://en.wikipedia.org/wiki/SQL_injection –
你確定它的'INSERT'慢,而不是'cURL'請求嗎?試着'回聲一些時間到頁面,以確保你知道它放緩的地方。 – vimist
請仔細閱讀http://www.php.net/manual/en/mysqli.multi-query.php –