如何抓取json数据并存储在数据库中

时间:2017-03-31 05:31:03

标签: php mysql

我正在尝试从json获取数据,我想将其保存在数据库中。 我有错误,请帮助我。下面是我的代码。

<?php

//My connection was ok

//read the json file contents
$url = ('http://api.football-data.org/v1/teams/61/players/');
$jsondata = file_get_contents($url);

//convert json object to php associative array
$data = json_decode($jsondata, true);
//print_r($data);

//get the employee details
foreach ($data['_links']['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//    //insert into mysql table
mysql_select_db($db, $conn); //database and connection 

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql = "INSERT INTO player ( Name, Position, Nationality, Market, Created)       
        VALUES( ?,?,?,?,?)";
// bind variables to insert query params
    mysqli_stmt_bind_param($sql, 'sss', $name, $posi, $nation, $market, $date);
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you <br/>";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

mysql_close($conn); //close of process or connection
?>

我试图首先打印我想要的值/数据,以确保 foreach 循环正常工作但我也遇到了错误:

注意:未定义的索引:第22行的C:\ xampp \ htdocs \ lab4 \ apitest.php中的玩家

警告:在第22行的C:\ xampp \ htdocs \ lab4 \ apitest.php中为foreach()提供的参数无效

警告:mysql_select_db()期望参数2是资源,第31行的C:\ xampp \ htdocs \ lab4 \ apitest.php中给出的对象

警告:mysqli_stmt_bind_param()要求参数1为mysqli_stmt,第38行的C:\ xampp \ htdocs \ lab4 \ apitest.php中给出的字符串

警告:mysql_query()期望参数2是资源,第40行的C:\ xampp \ htdocs \ lab4 \ apitest.php中给出的对象 错误:

这是我的json:

{

    "_links": {
        "self": {
            "href": "http://api.football-data.org/v1/teams/61/players"
        },
        "team": {
            "href": "http://api.football-data.org/v1/teams/61"
        }
    },
    "count": 25,
    "players": [
        {
            "name": "Marcos Alonso",
            "position": "Left-Back",
            "jerseyNumber": 3,
            "dateOfBirth": "1990-12-28",
            "nationality": "Spain",
            "contractUntil": "2021-06-30",
            "marketValue": "9,000,000 €"
        },
        {
            "name": "Marco van Ginkel",
            "position": "Central Midfield",
            "jerseyNumber": null,
            "dateOfBirth": "1992-12-01",
            "nationality": "Netherlands",
            "contractUntil": "2018-06-30",
            "marketValue": "7,000,000 €"
        },

请帮助我如何阅读想要的数据并成功存储在数据库中。

非常感谢!

2 个答案:

答案 0 :(得分:0)

尝试

foreach ($data['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

答案 1 :(得分:0)

您的数据访问方法存在问题。你写道:

foreach ($data['_links']['players'] as $myp) {

你必须改变它以获得正确的结构:

foreach ($data['players'] as $myp) {

因为玩家键不是 _links 的孩子。

第二个问题是如果你想将所有玩家插入数据库。您必须移动并插入并执行语句到foreach循环中。

希望这对你有帮助!