问题是只有部分 XML 数据被插入到我的 mysql 数据库中。应该将 10 个结果输入数据库,但结果在 2 到 8 个之间变化。我不知道它为什么这样做,我尝试添加一个 sleep 函数来减慢脚本速度,但插入数据库的数据永远不会像我在屏幕上回显时那么多。任何帮助将不胜感激..
function post_to_db($xml,$cat_id){
if ($xml->Items->Request->IsValid == 'True'){
$xml = $xml->Items->Item;
foreach($xml as $item){
$asin = (string)$item->ASIN;
$title = (string)$item->ItemAttributes->Title;
$content = (string)
$item->EditorialReviews->EditorialReview->Content;
$sku = (string)$item->ItemAttributes->SKU;
$brand = (string)$item->ItemAttributes->Brand;
$feature = (string)$item->ItemAttributes->Feature;
$model_no = (string)$item->ItemAttributes->Model;
$review = (string)$item->ItemLinks->ItemLink[5]->URL;
$check = "SELECT * FROM `products` WHERE `asin` = '$asin'";
$checked = mysql_query($check);
$numrows = mysql_num_rows($checked);
if ($numrows == 0){
$query = "INSERT INTO `products`".
"(`cat_id`,`asin`,`sku`,`brand`,".
"`model_no`,`title`,`content`,`feature`) ".
"VALUES".
"('$cat_id','$asin','$sku','$brand',".
"'$model_no','$title',".
"'$content','$feature')";
$result = mysql_query($query);
$post_id = mysql_insert_id();
$review_page[] = array($post_id=>$review);
}
}
}
return $review_page;
}
最佳答案
我的猜测是 XML 中的一些变量正在创建无效查询(它们是否包含引号?)
而不是每个变量都这样:
$asin = (string)$item->ASIN;
这样做:
$asin = mysql_real_escape_string((string)$item->ASIN);
如果问题仍然存在,请将 mysql_query
行更改为以下内容以进行调试:
$result = mysql_query($query) or die(mysql_error());
关于php - foreach循环中的数据插入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6850551/