php - 在 MySQL 中插入多个 JSON 列(使用 API)

标签 php mysql json

我正在尝试使用 API 存储体育数据 json 列,但无法使其正常工作。虽然我可以插入数据,但它只插入第一列结果并在所有后面的列上保持重复。默认情况下,它显示 50 列即将举行的足球比赛。我的问题是只有第一行结果是重复的..

这是代码:

//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);

上面的代码只是插入第一个 json 结果,并且它不断重复下一列(结果)..将不胜感激。

最佳答案

您遇到这个问题是因为您在 foreach 循环之外执行 mysql 查询。您必须在循环内执行查询。

做类似的事情

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);
}

关于php - 在 MySQL 中插入多个 JSON 列(使用 API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844392/

相关文章:

php - laravel 5.2 中的输入文件?

php - 优化 JavaScript CSS 下载

PHP Date - 时差格式化

mysql - 在rails应用程序中使用activerecord处理MySQL故障转移(主/从角色切换)

php - Javascript 和 PHP 数组值

mysql - 每个查询都会创建一个新的 CONNECTION_ID()

mysql:计算所有组中的重复行

python - 如何使用 Python 创建 JSON 对象的嵌套数组?

sql - 查询 JSON 列中的数组元素

javascript - 外部 JSON 和外部模板 - 无法同时工作