0

好的..我正在尝试从外部 JSON 页面获取信息到我的本地 MySQL 数据库(通过 xampp)。它不起作用..这是我的代码。

JSON页面

{
        "id": 219,
        "first_name": "Dimitar",
        "second_name": "Berbatov",
    "season_history": [
        ["2006/07", 2715, 12, 11, 0, 45, 0, 0, 0, 1, 0, 0, 26, 0, 91, 169],
        ["2007/08", 2989, 15, 11, 0, 56, 0, 0, 0, 3, 0, 0, 18, 0, 95, 177],
        ["2008/09", 2564, 9, 10, 0, 20, 0, 0, 0, 2, 0, 0, 14, 0, 95, 138],
        ["2009/10", 2094, 12, 6, 0, 13, 0, 0, 0, 1, 0, 0, 8, 0, 92, 130],
        ["2010/11", 2208, 21, 4, 8, 28, 0, 0, 0, 1, 0, 0, 26, 0, 92, 176],
        ["2011/12", 521, 7, 0, 2, 6, 0, 0, 0, 0, 0, 0, 5, 146, 89, 49]
}

我的代码.php

$con=mysqli_connect("SERVER","USERNAME","PASSWORD", "DATABASE") or die("Nope.");

//GETS THE PAGE WITH THE PLAYER DETAILS
$i = 219; //will loop this for every user later
$str = file_get_contents('http://fantasy.premierleague.com/web/api/elements/'.$i.'/');
$jsonarray = json_decode($str, true);

//PLAYER DETAILS
$id = $jsonarray['id'];
$firstname = addslashes($jsonarray['first_name']);
$secondname = addslashes($jsonarray['second_name']);

//Count how many seasons
$numberOfSeasons = count($jsonarray['season_history']);

//For Each Season
for($SeasonCount = 0; $SeasonCount < $numberOfSeasons; $SeasonCount++) {
    $whichSeason = $jsonarray['season_history'][$SeasonCount][0];
    $SeasonMins = $jsonarray['season_history'][$SeasonCount][1];
    $SeasonGoalsScored = $jsonarray['season_history'][$SeasonCount][2];
    $SeasonAssists = $jsonarray['season_history'][$SeasonCount][3];

mysqli_query
($con, "
SELECT EXISTS (SELECT 1 FROM myTable WHERE id='$id' AND whichSeason='$whichSeason')
UPDATE myTable SET 
    id = '$id', 
    whichSeason = '$whichSeason',
    SeasonMins = '$SeasonMins', 
    SeasonGoalsScored = '$SeasonGoalsScored', 
    SeasonAssists = '$SeasonAssists'
ELSE
INSERT INTO myTable (id, whichSeason, SeasonMins, SeasonGoalsScored, SeasonAssists) 
VALUES ('$id', '$whichSeason', '$SeasonMins', '$SeasonGoalsScored', '$SeasonAssists')
")
or die (mysqli_error($con));

}

笔记

  • 没有主键。我不知道哪个条目可以用作一个。

它应该做什么

  • 搜索myTable以查看条目是否已存在。
  • 如果没有匹配,添加它。
  • 如果它已经存在,请更新它。

如果您需要更多信息,请告诉我。我对 PDO 一无所知,但由于该数据库是本地数据库,并且该页面仅在我的浏览器上运行,所以我不需要它,对吗?

谢谢你提供的所有帮助。

4

1 回答 1

1

由于您使用的是 mysql,因此您应该能够使用并替换为查询。

首先,您要在 id 和 whichSeason 上添加主键

 ALTER TABLE myTable add primary key (id, whichSeason);

然后您可以将替换发出到查询中。

REPLACE INTO myTable 
    (id, whichSeason, SeasonMins, SeasonGoalsScored, SeasonAssists) 
VALUES 
    ('$id', '$whichSeason', '$SeasonMins', '$SeasonGoalsScored', '$SeasonAssists');
于 2013-07-11T06:10:00.487 回答