我想从大型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';
}
请帮助我做到。
答案 0 :(得分:0)
试试这个:
$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
]);
}
这里的主要区别在于您正在进行多次插入而不是一次大插入。