I'm trying to store sports data json column using API but I can't get it working properly. Though I can insert the data but it insert only the first column result and keep it duplicating on all the later columns. At default, it shows 50 column upcoming football matches. My problem is only the first line result is duplicating..
Here is the code:
//connect to mysql db
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "dname";
$conn = new mysqli($host, $user, $pass, $db) or die("ERROR:could not connect to
the database!!!");
//read the json file contents
$url = 'http://api.example.com/v1/events/upcoming?token=566645-
sl1uDzY3tVvv9M&league_id=78&sport_id=1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch) or die(curl_error($ch));
if ($data === false) {
$info = curl_getinfo($ch);
curl_close($ch);
die('error occured during curl exec. Additioanl info: ' .
var_export($info));
}
curl_close($ch);
$obj = json_decode($data, true);
foreach ($obj['results'] as $res) {
$league = $res['league']['name'];
$home = $res['home']['name'];
$away = $res['away']['name'];
$time = date("d/m h:i", $res['time']);
}
$sql = "INSERT INTO schedule(league, home, away, time)
VALUES('$league', '$home', '$away', '$time')";
$result = mysqli_query($conn, $sql);
if (!$result) {
die("ERROR :" . mysqli_error());
} else {
echo "Records has been successfully inserted";
}
//close the connection
mysqli_close($conn);
The above code just insert the first json result, and it keeps repeating for the next column (result).. Help will be appreciated.