使用PHP在MySQL数据库中插入JSON数据
我尝试使用PHP解析JSON文件。 然后我将提取的数据放入MySQL数据库中 这是我的JSON文件使用PHP在MySQL数据库中插入JSON数据,php,mysql,json,Php,Mysql,Json,我尝试使用PHP解析JSON文件。 然后我将提取的数据放入MySQL数据库中 这是我的JSON文件 {"u":[ {"text":"Chef salad is calling my name, I\u0027m so hungry!", "id_str":"28965131362770944", "created_at":"dom gen 23 24:00:00 +0000 2011", "user":
{"u":[
{"text":"Chef salad is calling my name, I\u0027m so hungry!",
"id_str":"28965131362770944",
"created_at":"dom gen 23 24:00:00 +0000 2011",
"user":
{"id_str":"27144739",
"screen_name":"LovelyThang80",
"name":"One of A Kind"}},
{....} //Other same code
}
这是我的PHP代码
<?php
//connect to mysql db
//read the json file contents
//convert json object to php associative array
$data = json_decode($jsondata, true);
//prepare variables for insert
$sqlu = "INSERT INTO user(id_user, screen_name, name)
VALUES ";
$sqlt = "INSERT INTO tweet(id_user, date, id_tweet, text)
VALUES ";
//I analyze the whole array and assign the values to variables
foreach ($data as $u => $z){
foreach ($z as $n => $line){
foreach ($line as $key => $value) {
switch ($key){
case 'text':
$text = $value;
break;
case 'id_str':
$id_tweet = $value;
break;
case 'created_at':
$date = $value;
break;
case 'user':
foreach ($value as $k => $v) {
switch($k){
case 'id_str':
$id_user = $v;
break;
case 'screen_name':
$screen_name = $v;
break;
case 'name':
$name = $v;
break;
}
}
//insert value into table
$sqlu .= "('".$id_user."', '".$screen_name."', '".$name."')";
break;
}
}
//insert value into table
$sqlt .= "('".$id_user."', '".$date."', '".$id_tweet."', '".$text."')";
}
}
?>
输出:
INSERT INTO user(id_user, screen_name, name)
VALUES ('27144739', 'LovelyThang80', 'One of A Kind')
INSERT INTO user(id_user, screen_name, name)
VALUES ('27144739', 'LovelyThang80', 'One of A Kind')('21533938', 'ShereKhan77', 'Loki Camina Cielos ')
INSERT INTO user(id_user, screen_name, name)
VALUES ('27144739', 'LovelyThang80', 'One of A Kind')('21533938', 'ShereKhan77', 'Loki Camina Cielos ')('45378162', 'Cosmic_dog', 'Pablo')
我也一样
echo $sqlt;
为什么?您忘记在值之间添加:
插入userid\u user、screen\u name、name
价值观“27144739”、“LovelyThang80”、“独一无二”、“21533938”、“ShereKhan77”、“Loki Camina Cielos”
并且一次只能插入一条insert语句。您忘记在值之间添加:
插入userid\u user、screen\u name、name
价值观“27144739”、“LovelyThang80”、“独一无二”、“21533938”、“ShereKhan77”、“Loki Camina Cielos”
一次只能插入一条insert语句。您在哪里运行此查询??我指的是执行查询的命令,例如mysqli_query$sqlt,$connectionI删除它们只是为了输入这个问题,但是我把它们放在了真正的代码中,你在哪里运行这个查询??我指的是执行查询的命令,例如mysqli_query$sqlt,$connectionI删除它们只是为了输入这个问题,但是我把它们放在了真正的代码中,我想我们可以插入我们想要的任何内容。是的,但这取决于插入方法。PDO不支持多查询语句。我想我们可以插入任意数量的语句。是的,但这取决于插入方法。PDO不支持多查询语句。
echo $sqlt;