使用php将json对象中的元素插入数据库

bq3bfh9z  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(332)

我只是一个学生,所以如果这个帖子不清楚,请提前道歉。
我正在将产品数据从json响应导入产品数据库。我的目标是将json对象中的元素插入到数据库中。
目前,我得到了“未定义索引:产品”的错误和纠正时,“无效foreach语句”的错误。真的很难理解我的错误在哪里。
如果有人能看看这段代码,看看我做错了什么,我会非常感激。

代码:

<?php
$params = http_build_query(array(
  "api_key" => "***",
  "format" => "json"
));

$result = file_get_contents(
    'https://www.parsehub.com/api/v2/projects/***/last_ready_run/data?'.$params,
    false,
    stream_context_create(array(
        'http' => array(
            'method' => 'GET'
        )
    ))
);

$result=gzdecode($result);
$parsed_result = json_decode($result, true);
$product[] = $parsed_result['product'];
    foreach($product as $item){ 
        $updated = $item['updated'];
        $name = $item['name'];
        $url = $item['url'];
        $currentPrice = $item['currentPrice'];
        $originalPrice = $item['originalPrice'];
        $picture = $item['picture'];
        $brand = $item['brand'];
        $model = $item['model'];

        require 'db_configuration.php';
        $sql2 = "INSERT INTO storeA (name, url, currentPrice, originalPrice, picture, brand, model, updated) VALUES ('{$name}',{$url},{$currentPrice},{$originalPrice},{$picture},{$brand},{$model},{$updated})";
        $result = run_sql($sql2);

    }
?>

json码:

{
  "links": [
    {
      "link": "http://www.***.com",
      "product": [
        {
          "updated": "****",
          "name": "****",
          "url": "****",
          "currentPrice": "$****",
          "originalPrice": "$****",
          "picture": "http://****.jpg",
          "picture_url": "****",
          "brand": "***",
          "extra": "****"
        },
        {
          "updated": "****",
          "name": "****",
          "url": "****",
          "currentPrice": "$****",
          "originalPrice": "$****",
          "picture": "http://****.jpg",
          "picture_url": "****",
          "brand": "***",
          "extra": "****"
        }
      ]
    },
    {
      "link": "http://www.***.com",
      "product": [
        {
          "updated": "****",
          "name": "****",
          "url": "****",
          "currentPrice": "$****",
          "originalPrice": "$****",
          "picture": "http://****.jpg",
          "picture_url": "****",
          "brand": "***",
          "extra": "****"
        },
        {
          "updated": "****",
          "name": "****",
          "url": "****",
          "currentPrice": "$****",
          "originalPrice": "$****",
          "picture": "http://****.jpg",
          "picture_url": "****",
          "brand": "***",
          "extra": "****"
        }
      ]
    },
    {
      "link": "http://www.***.com",
      "product": [
        {
          "updated": "****",
          "name": "****",
          "url": "****",
          "currentPrice": "$****",
          "originalPrice": "$****",
          "picture": "http://****.jpg",
          "picture_url": "****",
          "brand": "***",
          "extra": "****"
        },
        {
          "updated": "****",
          "name": "****",
          "url": "****",
          "currentPrice": "$****",
          "originalPrice": "$****",
          "picture": "http://****.jpg",
          "picture_url": "****",
          "brand": "***",
          "extra": "****"
        }
      ]
    }
  ]
}

数据库配置

<?php
DEFINE('DATABASE_HOST', 'localhost');
DEFINE('DATABASE_DATABASE', '***');
DEFINE('DATABASE_USER', 'root');
DEFINE('DATABASE_PASSWORD', '');

$db = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_DATABASE);
$db->set_charset("utf8");
function run_sql($sql_script)
{
    global $db;
    // check connection
    if ($db->connect_error)
    {
        trigger_error(print_r(debug_backtrace()).'.Database connection failed: '  . $db->connect_error, E_USER_ERROR);
    }
    else
    {
        $result = $db->query($sql_script);
        if($result === false)
        {
            trigger_error('Stack Trace: '.print_r(debug_backtrace()).'Invalid SQL: ' . $sql_script . '; Error: ' . $db->error, E_USER_ERROR);
        }
        else if(strpos($sql_script, "INSERT")!== false)
        {
            return $db->insert_id;
        }
        else
        {
            return $result;
        }
    }
}

?>
fquxozlt

fquxozlt1#

从var\u转储 json_decode($result, true) -阵列结构为:

array(1) {
  'links' =>
  array(1) {
    [0]
    array(2) {
      'link' =>
      string(18) "http://www.***.com"
      'product' =>
      array(2) {
        ...
      }
    }
  }
}

所以, $parsed_result 是一个数组,其中有一个元素 links 作为关键。此元素包含链接/产品对的数组。
因此,如果您想获得json响应中的所有产品,需要执行以下操作:

foreach ($link in $parsed_results['links']) {
    foreach ($product in $link['product']) {
        // construct your array
    }
}

这将起作用-但是您的数据库查询会受到sql注入攻击。决不应使用插值将变量注入sql查询-决不应这样做:

$sql2 = "INSERT INTO storeA (name, url, currentPrice, originalPrice, picture, brand, model, updated) VALUES ('{$name}',{$url},{$currentPrice},{$originalPrice},{$picture},{$brand},{$model},{$updated})";

相反,您应该使用带参数的准备好的查询:

$insertProductQuery = mysqli_prepare("INSERT INTO storeA (name, url, currentPrice, originalPrice, picture, brand, model, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

mysqli_stmt_bind_param($insertProductQuery, 'ssddssss', $name, $url, $currentPrice, $originalPrice, $picture, $brand, $model, $updated);

(我假设您的数据库模式具有参数类型-尽管您也不应该使用real/float/double来存储货币值)
更好的是,使用pdo,您可以使用命名参数。

相关问题