php - Difficulty taking info from JSON page and putting into MySQL -
ok.. i'm trying info external json page local mysql database (via xampp). it's not working.. here code.
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 page player details $i = 219; //will loop 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 mytable id='$id' , whichseason='$whichseason') update mytable set id = '$id', whichseason = '$whichseason', seasonmins = '$seasonmins', seasongoalsscored = '$seasongoalsscored', seasonassists = '$seasonassists' else insert mytable (id, whichseason, seasonmins, seasongoalsscored, seasonassists) values ('$id', '$whichseason', '$seasonmins', '$seasongoalsscored', '$seasonassists') ") or die (mysqli_error($con)); }
note
- there no primary key. don't know entry used one.
what should do
- search
mytable
see if entry exists. - if no match, add it.
- if it's there, update it.
please let me know if need more information. don't know pdo, database local , page run on browser only, don't need right?
thanks can give.
since using mysql should able use , replace into query.
first off want add primary key on id , whichseason
alter table mytable add primary key (id, whichseason);
then can issue replace query.
replace mytable (id, whichseason, seasonmins, seasongoalsscored, seasonassists) values ('$id', '$whichseason', '$seasonmins', '$seasongoalsscored', '$seasonassists');
Comments
Post a Comment