【问题标题】:How to Insert the large json file into mysql with php?如何使用 php 将大的 json 文件插入 mysql?
【发布时间】:2016-06-16 20:13:26
【问题描述】:

我想从大型 json 文件中读取并用 php 将其存储在数据库中。

我为解析和插入文件编写了这段代码,但最后一个查询不起作用。

public function insert_from_json() {
    $json = '
            [            
            {
            "name": "The Adventurer",
            "year": 1917,
            "country": "USA",
            "durationMinutes": 24,
            "director": "Charles Chaplin"
            },
            {
            "name": "Mest kinematograficheskogo operatora",
            "year": 1912,
            "country": "Russia",
            "durationMinutes": 12,
            "director": "Wladyslaw Starewicz"
            }
            ]';

    $result = json_decode($json);

    $vals = '';
    foreach ($result as $key => $value) {

        if ($value) {
            $vals.="('$value->name','$value->year','$value->country','$value->durationMinutes','$value->director'),";
        }
    }
    $vals = trim($vals, ',');
    $stmt = $this->conn->prepare("INSERT INTO film (name,year,country,durationMinutes,director) VALUES ($vals)");
    $stmt->execute();
    echo 'successfully';
}

请帮我做。

【问题讨论】:

  • 我觉得这必须在某个地方覆盖。
  • 你得到什么错误?是否生成有效的 SQL?
  • 最后的括号是多余的。删除这些,我怀疑它会起作用 - 但这看起来不太安全!
  • "('{$value->name}', 等...
  • 这样构建查询违背了使用准备好的语句的目的。

标签: php mysql json parsing


【解决方案1】:

试试这个:

$json = '[            
    {
        "name": "The Adventurer",
        "year": 1917,
        "country": "USA",
        "durationMinutes": 24,
        "director": "Charles Chaplin"
    },
    {
        "name": "Mest kinematograficheskogo operatora",
        "year": 1912,
        "country": "Russia",
        "durationMinutes": 12,
        "director": "Wladyslaw Starewicz"
    }
]';

$result = json_decode($json);

$stmt = $this->conn->prepare("
    INSERT INTO film (name, year, country, durationMinutes, director) 
    VALUES (:name, :year, :country, :durationMinutes, :director)
");

// loop through each object
foreach ($result as $r) {
    // and insert it into the database
    $stmt->execute([
        ':name' => $r->name,
        ':year' => $r->year, 
        ':country' => $r->country, 
        ':durationMinutes' => $r->durationMinutes, 
        ':director' => $r->director
    ]);
}

这里的主要区别是您正在执行多次插入而不是一次大插入。

【讨论】:

  • 我非常参与解决这个问题。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 2021-05-22
  • 2011-07-05
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多