Try this.
You are just executing the last query cause you mysqli_query()
is outside loop.
Method 1:
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
//read the json file contents
$jsondata = file_get_contents('prova.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
foreach ($data as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$sqlu = "INSERT INTO user(id_user, screen_name, name)
VALUES ('".$id_user."', '".$screen_name."', '".$name."')";
if(!mysqli_query($con, $sqlu))
{
die('Error : ' . mysql_error());
}
}
}
?>
Method 2:
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
//read the json file contents
$jsondata = file_get_contents('prova.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
$values = "";
foreach ($data as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$values .= "('".$id_user."', '".$screen_name."', '".$name."'),";
}
}
if(!empty($values)) {
$values = substr($values, 0, -1);
$sqlu = "INSERT INTO user(id_user, screen_name, name) VALUES {$values}";
if(!mysqli_query($con, $sqlu))
{
die('Error : ' . mysql_error());
}
}
?>
Answer for multiple files:
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
$files = array("prova.json", "file2.json");
foreach ($files as $file) {
//read the json file contents
$jsondata = file_get_contents($file);
//convert json object to php associative array
$data = json_decode($jsondata, true);
$values = "";
foreach ($data as $u => $z) {
foreach ($z as $n => $line) {
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$values .= "('" . $id_user . "', '" . $screen_name . "', '" . $name . "'),";
}
}
if (!empty($values)) {
$values = substr($values, 0, -1);
$sqlu = "INSERT INTO user(id_user, screen_name, name) VALUES {$values}";
if (!mysqli_query($con, $sqlu)) {
die('Error : ' . mysql_error());
}
}
}
?>