SQL仅将最后一个元素/ Json对象存储到数据库中

时间:2017-04-01 22:33:05

标签: php json

尝试从API中获取数据,并存储在数据库中。但是数组的元素/对象存储在数据库中。 有关如何获取存储在数据库中的所有数据的任何帮助将不胜感激。 我的PHP代码:

$data = json_decode($jsondata, true);
//print_r($data);

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

//insert into mysql table
mysqli_select_db($conn, $db); //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 staffdb ( Name, Position, Nationality, Market, Created)       
        VALUES('$name', '$posi', '$nation', '$market', '$date')";
}
//if the connection is sucessful, display regards message
if (mysqli_query($conn, $sql)) {
    echo "Thank you <br/>";
} else {   //if the connection is not established
    die('Error: ' . mysqli_error());
}

mysqli_close($conn); //close of process or connection

api看起来像这样:

"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 €"
    },

非常感谢!

0 个答案:

没有答案