我正在尝试从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 €"
        },


请帮助我如何读取所需的数据并将其成功存储在数据库中。

非常感谢!

最佳答案

您的数据访问方法有问题。你写:

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


您必须将其更改为正确的结构:

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


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

第二个问题是是否要将所有播放器插入数据库。您必须移动并在foreach循环中插入并执行语句。

希望这对您有所帮助!

10-07 12:53
查看更多