foreach循环中的数据插入问题

时间:2011-07-27 20:05:20

标签: php mysql foreach

问题是只有部分XML数据被插入到我的mysql数据库中。应该将10个结果输入数据库,但它在2到8个结果之间变化。我不知道为什么会这样做,我已经尝试添加一个睡眠功能来减慢脚本速度,但插入数据库的数据永远不会像我在屏幕上回显时那样多。任何帮助将不胜感激..

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;    
}

1 个答案:

答案 0 :(得分:2)

我的猜测是你的一些XML变量正在创建一个无效的查询(它们是否包含引号?)

而不是每个变量:

$asin           = (string)$item->ASIN;

请改为:

$asin = mysql_real_escape_string((string)$item->ASIN);

如果问题仍然存在,请将mysql_query行更改为此内容以进行调试:

$result = mysql_query($query) or die(mysql_error());