php - foreach循环中的数据插入问题

标签 php mysql foreach

问题是只有部分 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/

相关文章:

php - 使用数组在 foreach 循环中将 PHP 变量设置为 MySQL 数据

javascript - 如何遍历由 Object.defineProperty 创建的对象属性

php - ZF2 使用 PHP5 与 PHP7

java - 使用 JDBC 更新查询 mysql

PHP unlink 正在请求一个字符串并试图给它 sql 字符串

sql - 如何迭代嵌套表类型?

php - 用于检测用户是否是特定用户组成员的自定义代码的小问题

php - 如何使用 htaccess URL php 变量进行 301 重定向

php - 资源解释为文档但使用 MIME 类型 application/x-javascript 传输

sql - 多个表更新中的MySQL错误