开发者

Data insert problem within foreach loop

The problem is that only some of the XML data is being Inserted into the my mysql database. 10 results are supposed to be entered into the database but it varies between 2 and 8 results. I have no idea why it is doing this and I have tried adding a sleep function to slow the script down, but the data that is inserted into the data base is never as much as when I echo it out on screen. Any help would be much appreciated..

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)
       开发者_如何学Python                      $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;    
}


My guess would be some of your variables from XML are creating an invalid query (do they contain quotes?)

Instead of this for each variable:

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

Do this instead:

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

If the problem still persists, change your mysql_query line to this for debugging:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜