难以从JSON页面获取信息并放入MySQL

时间:2013-07-11 05:49:24

标签: php javascript mysql json

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

JSON PAGE

{
        "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]
}

mycode.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一无所知,但由于这个数据库是本地的,而且页面只在我的浏览器上运行,我不需要它吗?

感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:1)

由于您使用的是mysql,因此您应该可以使用replace into查询。

首先,您要在id和whichSeason

上添加主键
 ALTER TABLE myTable add primary key (id, whichSeason);

然后您可以发出替换为查询。

REPLACE INTO myTable 
    (id, whichSeason, SeasonMins, SeasonGoalsScored, SeasonAssists) 
VALUES 
    ('$id', '$whichSeason', '$SeasonMins', '$SeasonGoalsScored', '$SeasonAssists');