json decode all pages at once - php

I have a problem. I want to json decode the API from https://www.easports.com/fifa/ultimate-team/api/fut/item?page=1, but this only contains 24 players and it has 771(!) pages so that will take forever if you do it one player at one. How can I do it all at once. I currently have this script:
<?php
$conn = mysqli_connect("localhost","u1715p547","L0yRM6pd","u1715p547_ps");
mysqli_set_charset($conn,"utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$page_data_url = "https://www.easports.com/fifa/ultimate-team/api/fut/item?page=1";
// Get the JSON file from EASports
$page_data_plain = file_get_contents($page_data_url);
// Decode the JSON file to a PHP array
$page_data_json = json_decode($page_data_plain, true);
// Get the total pages count
$total_pages_count = $page_data_json['totalPages'];
// Loop through each page
for ($page = 1; $page <= $total_pages_count; $page++){
// Get the EASports JSON per specific page
$item_url = 'https://www.easports.com/fifa/ultimate-team/api/fut/item?page='.$page;
// Get the JSON file from EASports
$item_data_plain = file_get_contents($item_url);
// Decode the JSON file to a PHP array
$item_data_json = json_decode($item_data_plain, true);
// Count the amount of items
$total_items_count = $item_data_json['count'];
// Loop through all items, extract the values and insert in DB
for ($c = 0; $c < $total_items_count; $c++) {
$commonname00 = $item_data_json[$c]['commonName'];
$commonname = str_replace("'", "''", $commonname00);
$firstname00 = $item_data_json[$c]['firstName'];
$firstname = str_replace("'", "''", $firstname00);
$lastname00 = $item_data_json[$c]['lastName'];
$lastname = str_replace("'", "''", $lastname00);
$playerimg = $item_data_json[$c]['headshotImgUrl'];
$leagueid = $item_data_json[$c]['league']['id'];
$nationsmall = $item_data_json[$c]['nation']['imageUrls']['small'];
$nationnormal = $item_data_json[$c]['nation']['imageUrls']['medium'];
$nationlarge = $item_data_json[$c]['nation']['imageUrls']['large'];
$nationid = $item_data_json[$c]['nation']['id'];
$clubsmall = $item_data_json[$c]['club']['imageUrls']['normal']['small'];
$clubnormal = $item_data_json[$c]['club']['imageUrls']['normal']['medium'];
$clublarge = $item_data_json[$c]['club']['imageUrls']['normal']['large'];
$clubid = $item_data_json[$c]['club']['id'];
$largeImgUrl = $item_data_json[$c]['headshot']['largeImgUrl'];
$medImgUrl = $item_data_json[$c]['headshot']['medImgUrl'];
$smallImgUrl = $item_data_json[$c]['headshot']['smallImgUrl'];
$largeSpecImgUrl = $item_data_json[$c]['specialImages']['largeTOTWImgUrl'];
$medSpecImgUrl = $item_data_json[$c]['specialImages']['medTOTWImgUrl'];
$pos = $item_data_json[$c]['position'];
$ps = $item_data_json[$c]['playStyle'];
$heig = $item_data_json[$c]['height'];
$weig = $item_data_json[$c]['weight'];
$bd = $item_data_json[$c]['birthdate'];
$age = $item_data_json[$c]['age'];
$acc = $item_data_json[$c]['acceleration'];
$agg = $item_data_json[$c]['aggression'];
$agi = $item_data_json[$c]['agility'];
$bal = $item_data_json[$c]['balance'];
$ball = $item_data_json[$c]['ballcontrol'];
$foot = $item_data_json[$c]['foot'];
$sm = $item_data_json[$c]['skillMoves'];
$cro = $item_data_json[$c]['crossing'];
$cur = $item_data_json[$c]['curve'];
$dri = $item_data_json[$c]['dribbling'];
$fin = $item_data_json[$c]['finishing'];
$fca = $item_data_json[$c]['freekickaccuracy'];
$gkd = $item_data_json[$c]['gkdiving'];
$gkh = $item_data_json[$c]['gkhandling'];
$gkk = $item_data_json[$c]['gkkicking'];
$gkp = $item_data_json[$c]['gkpositioning'];
$gkr = $item_data_json[$c]['gkreflexes'];
$hea = $item_data_json[$c]['headingaccuracy'];
$int = $item_data_json[$c]['interceptions'];
$jum = $item_data_json[$c]['jumping'];
$lop = $item_data_json[$c]['longpassing'];
$los = $item_data_json[$c]['longshots'];
$mar = $item_data_json[$c]['marking'];
$pen = $item_data_json[$c]['penalties'];
$poi = $item_data_json[$c]['positioning'];
$pot = $item_data_json[$c]['potential'];
$rea = $item_data_json[$c]['reactions'];
$shp = $item_data_json[$c]['shortpassing'];
$sho = $item_data_json[$c]['shotpower'];
$slt = $item_data_json[$c]['slidingtackle'];
$spr = $item_data_json[$c]['sprintspeed'];
$stt = $item_data_json[$c]['standingtackle'];
$sta = $item_data_json[$c]['stamina'];
$str = $item_data_json[$c]['strength'];
$vis = $item_data_json[$c]['vision'];
$vol = $item_data_json[$c]['volleys'];
$wf = $item_data_json[$c]['weakFoot'];
$traits = $item_data_json[$c]['traits'][$c];
$traits1 = $item_data_json[$c]['traits']['1'];
$traits2 = $item_data_json[$c]['traits']['2'];
$traits3 = $item_data_json[$c]['traits']['3'];
$traits4 = $item_data_json[$c]['traits']['4'];
$specialities = $item_data_json[$c]['specialities'][$c];
$specialities1 = $item_data_json[$c]['specialities']['1'];
$specialities2 = $item_data_json[$c]['specialities']['2'];
$specialities3 = $item_data_json[$c]['specialities']['3'];
$specialities4 = $item_data_json[$c]['specialities']['4'];
$specialities5 = $item_data_json[$c]['specialities']['5'];
$specialities6 = $item_data_json[$c]['specialities']['6'];
$specialities7 = $item_data_json[$c]['specialities']['7'];
$specialities8 = $item_data_json[$c]['specialities']['8'];
$specialities9 = $item_data_json[$c]['specialities']['9'];
$specialities10 = $item_data_json[$c]['specialities']['10'];
$atk = $item_data_json[$c]['atkWorkRate'];
$def = $item_data_json[$c]['defWorkRate'];
$pty = $item_data_json[$c]['playerType'];
$pace = $item_data_json[$c]['attributes'][$c]['value'];
$shot = $item_data_json[$c]['attributes']['1']['value'];
$pass = $item_data_json[$c]['attributes']['2']['value'];
$drib = $item_data_json[$c]['attributes']['3']['value'];
$deff = $item_data_json[$c]['attributes']['4']['value'];
$phys = $item_data_json[$c]['attributes']['5']['value'];
$nameof00 = $item_data_json[$c]['name'];
$nameof = str_replace("'", "''", $nameof00);
$qua = $item_data_json[$c]['quality'];
$color = $item_data_json[$c]['color'];
$GK = $item_data_json[$c]['isGK'];
$posfull = $item_data_json[$c]['positionFull'];
$price = $item_data_json[$c]['discardValue'];
$id = $item_data_json[$c]['id'];
$baseId = $item_data_json[$c]['baseId'];
$rating = $item_data_json[$c]['rating'];
$sql = "INSERT IGNORE INTO `players`(`commonName`, `firstName`, `headshotImgUrl`, `lastName`, `leagueid`, `nationimageUrlssmall`, `nationimageUrlsmedium`, `nationimageUrlslarge`, `nationid`, `clubimageUrlsnormalsmall`, `clubimageUrlsnormalmedium`, `clubimageUrlsnormallarge`, `clubid`, `headshotlargeImgUrl`, `headshotmedImgUrl`, `headshotsmallImgUrl`, `specialImageslargeTOTWImgUrl`, `specialImagesmedTOTWImgUrl`, `position`, `playStyle`, `height`, `weight`, `birthdate`, `age`, `acceleration`, `aggression`, `agility`, `balance`, `ballcontrol`, `foot`, `skillMoves`, `crossing`, `curve`, `dribbling`, `finishing`, `freekickaccuracy`, `gkdiving`, `gkhandling`, `gkkicking`, `gkpositioning`, `gkreflexes`, `headingaccuracy`, `interceptions`, `jumping`, `longpassing`, `longshots`, `marking`, `penalties`, `positioning`, `potential`, `reactions`, `shortpassing`, `shotpower`, `slidingtackle`, `sprintspeed`, `standingtackle`, `stamina`, `strength`, `vision`, `volleys`, `weakFoot`, `traits0`, `traits1`, `traits2`, `traits3`, `specialities0`, `specialities1`, `specialities2`, `specialities3`, `specialities4`, `specialities5`, `specialities6`, `specialities7`, `specialities8`, `atkWorkRate`, `defWorkRate`, `playerType`, `attributes0value`, `attributes1value`, `attributes2value`, `attributes3value`, `attributes4value`, `attributes5value`, `name`, `quality`, `color`, `isGK`, `positionFull`, `discardValue`, `id`, `baseId`, `rating`, `specialities9`, `specialities10`, `traits4`)
VALUES ('$commonname', '$firstname', '$playerimg', '$lastname', $leagueid, '$nationsmall', '$nationnormal', '$nationlarge',
$nationid, '$clubsmall', '$clubnormal', '$clublarge', $clubid, '$largeImgUrl', '$medImgUrl',
'$smallImgUrl', '$largeSpecImgUrl', '$medSpecImgUrl', '$pos', '$ps', $heig, $weig, '$bd', $age, $acc, $agg, $agi, $bal, $ball, '$foot', $sm, $cro, $cur, $dri,
$fin, $fca, $gkd, $gkh, $gkk, $gkp, $gkr, $hea, $int, $jum, $lop, $los, $mar, $pen, $poi, $pot, $rea, $shp, $sho, $slt, $spr, $stt, $sta, $str, $vis, $vol, $wf,
'$traits', '$traits1', '$traits2', '$traits3', '$specialities', '$specialities1', '$specialities2', '$specialities3', '$specialities4', '$specialities5',
'$specialities6', '$specialities7', '$specialities8', '$atk', '$def', '$pty', $pace, $shot, $pass, $drib, $deff, $phys, '$nameof', '$qua', '$color', '$GK',
'$posfull', '$price', $id, $baseId, $rating, '$specialities9', '$specialities10', '$traits4')";
echo $sql;
if(!$result = $conn->query($sql))
{
die("<script type='text/javascript'>alert(Fault);</script>");
}
}
}
?>
It just gives me this:
INSERT IGNORE INTO `players`(`commonName`, `firstName`, `headshotImgUrl`, `lastName`, `leagueid`, `nationimageUrlssmall`, `nationimageUrlsmedium`, `nationimageUrlslarge`, `nationid`, `clubimageUrlsnormalsmall`, `clubimageUrlsnormalmedium`, `clubimageUrlsnormallarge`, `clubid`, `headshotlargeImgUrl`, `headshotmedImgUrl`, `headshotsmallImgUrl`, `specialImageslargeTOTWImgUrl`, `specialImagesmedTOTWImgUrl`, `position`, `playStyle`, `height`, `weight`, `birthdate`, `age`, `acceleration`, `aggression`, `agility`, `balance`, `ballcontrol`, `foot`, `skillMoves`, `crossing`, `curve`, `dribbling`, `finishing`, `freekickaccuracy`, `gkdiving`, `gkhandling`, `gkkicking`, `gkpositioning`, `gkreflexes`, `headingaccuracy`, `interceptions`, `jumping`, `longpassing`, `longshots`, `marking`, `penalties`, `positioning`, `potential`, `reactions`, `shortpassing`, `shotpower`, `slidingtackle`, `sprintspeed`, `standingtackle`, `stamina`, `strength`, `vision`, `volleys`, `weakFoot`, `traits0`, `traits1`, `traits2`, `traits3`, `specialities0`, `specialities1`, `specialities2`, `specialities3`, `specialities4`, `specialities5`, `specialities6`, `specialities7`, `specialities8`, `atkWorkRate`, `defWorkRate`, `playerType`, `attributes0value`, `attributes1value`, `attributes2value`, `attributes3value`, `attributes4value`, `attributes5value`, `name`, `quality`, `color`, `isGK`, `positionFull`, `discardValue`, `id`, `baseId`, `rating`, `specialities9`, `specialities10`, `traits4`) VALUES ('', '', '', '', , '', '', '', , '', '', '', , '', '', '', '', '', '', '', , , '', , , , , , , '', , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', , , , , , , '', '', '', '', '', '', , , , '', '', '')

You can't. You have to call it X times where X corresponds to number of pages.
You should ask authors if they could give you entire block of data in single call.

Related

Problem with the generation of csv file with condition

The following php code allows me to retrieve from a database the information of the orders of the day in order to export them in a csv file.
However I also have a file ArticleStock.csv which contains information on the products: ID and Name but which are different from those present in the database. I found a way to link the two by adding the IDs from the ArticleStock file to the product reference field.
Unfortunately this does not work well because the following program outputs a csv file with only the corresponding value found and not all the others
<?php
require_once 'dbconfig.php';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT o.id_order ,
c.id_customer, c.firstname, c.lastname,
a.address1, a.address2, a.postcode,
a.city,a.phone,
c.email,
a.phone_mobile,
od.product_id, od.product_name,
p.reference,
od.product_quantity, od.product_price,
o.total_paid_tax_incl,
c.id_customer,
op.date_add, op.amount, op.payment_method
FROM mod582_orders o
INNER JOIN mod582_customer c ON o.id_customer = c.id_customer
INNER JOIN mod582_address a ON o.id_address_delivery = a.id_address
INNER JOIN mod582_order_detail od ON o.id_order = od.id_order
INNER JOIN mod582_order_payment op ON o.reference = op.order_reference
INNER JOIN mod582_product p ON p.id_product = od.product_id
WHERE CAST(o.date_add AS DATE) like "2022-12%";';
$r = $pdo->query($sql);
$tab = [];
$tab[] = ['ORDNOORDER', 'ORDREFCUSORDER', 'ORDNOCOSTNUMBER', 'ORDNOCUSTOMER', 'ORDCUSTOMERCODE', 'ORDCUSCAT', 'ORDTYPE', 'ORDCURRENCY', 'ORDCURRENCYRATE', 'ORDDESIGNATION',
'ORDREPCODE', 'ORDPORT', 'ORDPORTTYPE', 'ORDPORTRATE', 'DEONOORDER', 'DEOCOMMENT', 'DEOCOUNTRY', 'DEONAME', 'DEOFIRSTNAME', 'DEOADDRESS1', 'DEOADDRESS2', 'DEOZIPCODE', 'DEOCITY',
'DEOPHONE', 'DEOMAIL', 'DEOPHONEPORTABLE', 'ODLNOORDER', 'ODLNOORDERLINE', 'ODLNOARTICLE', 'ODLARTDESIGN', 'REFERENCEPRODUIT', 'ODLQUANTITYORDER', 'ODLTTCCURUPRICE', 'ODLCODEPARCELLEFLEU',
'PAYNUMPAYMENT', 'PAYNOCUSTOMER', 'PAYNOORDER', 'PAYNOCURRENCY', 'PAYDATEPAYMENT', 'PAYPAYMENTTTCCUR', 'PAYCURRENCYRATE', 'PAYCONTREPARTIE'];
$odrline = 0; // start with zero, as incremented before first written out
$prevordernumber = 0; // pick a number that is not a valid order number
$file = fopen("ArticlesStock.csv", "r");
$rowcsv = 0;
while (!feof($file)) {
$thisLine = fgets($file);
$CSVData[$rowcsv] = explode(";", $thisLine);
$rowcsv++;
}
fclose($file);
$numRows = sizeof($CSVData);
$rowcsv = 0;
while ($rs = $r->fetch(PDO::FETCH_ASSOC)) {
$refproduit = $rs['reference'];
while ($rowcsv < $numRows) {
if ($CSVData[$rowcsv][0] == $refproduit) {
$idproduct = $CSVData[$rowcsv][0];
$nameproduct = $CSVData[$rowcsv][2];
if ($prevordernumber != $rs['id_order']) {
$odrline++;
$baseDate = strtotime($rs['date_add']);
$formatDate = date("d/m/Y", $baseDate);
$tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'],
$rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline,
$idproduct, $nameproduct, $rs['reference'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], 'EUR', $formatDate, $rs['amount'], '1', 'VIR'];
} else {
$tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'],
$rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline,
$rs['product_id'], $rs['product_name'], $rs['reference'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], '', '', '', ''];
}
}
$rowcsv++;
}
$prevordernumber = $rs['id_order'];
}
// write $tab to file
$date = date('d-m-y');
$fichier_csv = new SplFileObject('Vinistoria/Out/Commande/commande_STOCK_' . $date . '.csv', 'w');
foreach ($tab as $ligne) {
$fichier_csv->fputcsv($ligne, ';');
}
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
CSV return by my code :
And what i need :
So i need to replace my csv file ODLNOARTICLE and ODLARTDESIGN by the IDs and Names of products present in the file ArticleStock whose ID is equal to the reference field of my products recovered by my SQL query

How to insert a big amount of data in mysql database via PHP

I have this function to insert some data in my mysql database:
function insertRow($conn, $row, $header) {
// find indexes
// vorname
$firstNameIndex = array_search('vorname', $header, true);
// name / nachname
$lastNameIndex = array_search('name', $header, true);
if($lastNameIndex === false) $lastNameIndex = array_search('nachname', $header, true);
// anrede
$anredeIndex = array_search('anrede', $header, true);
// street
$streetIndex = array_search('straße', $header, true);
// Hausnummer
$hausnummerIndex = array_search('hausnummer', $header, true);
// Telefon
$telefonIndex = array_search('telefon', $header, true);
// PLZ
$plzIndex = array_search('plz', $header, true);
// ORT
$ortIndex = array_search('ort', $header, true);
$anrede = $row[$anredeIndex];
$firstName = $row[$firstNameIndex];
$lastName = $row[$lastNameIndex];
$street = $row[$streetIndex];
$houseNumber = $row[$hausnummerIndex];
$telefon = $row[$telefonIndex];
$plz = $row[$plzIndex];
$ort = $row[$ortIndex];
$title = 'unbekannt';
$geburtsdatum = 0;
$hnr_zusatz = "";
$timestamp = time();
$sql = <<<EOSQL
INSERT INTO adressen (anrede, vorname, nachname, strasse, hnr, telefon1, id_lieferung, priv_gew,
status, titel, geburtsdatum, hnr_zusatz, plz, ort, telefon2, mail, sperrung, sperrgrund, optin,
optindat, timestamp, zusatz1) VALUES ("$anrede", "$firstName", "$lastName", "$street",
"$houseNumber", "$telefon", 0, 0, 0, "$title", $geburtsdatum, "$hnr_zusatz", "$plz", "$ort", 0, "",
0, 0, 0, 0, $timestamp, 0);
EOSQL;
if (!$conn->query($sql) === TRUE) {
echo "Error: cant add this row " . $sql . "<br/>" . $conn->error;
print_r($row);
echo "___________________<br/>";
}
}
It works for small data but when I try it with a file more than 4 MB it doesn't work. I do not have access to the php.ini file sadly. These inserts come originally from an excel file. I wanted to try plupload but didn't understand how to implement it to my method.

How to use Plupload for insert statements in PHP

I have a php porgram which inserts data from an excel file to the mysql database but it doesn't work with files bigger than 4 MB and since I do not have access to the php.ini file I thought of chunking the insert statements. I found plupload but didn't figure out how to use it for insert statements. Any other method would be fine as well.
function insertRow($conn, $row, $header) {
// find indexes
// vorname
$firstNameIndex = array_search('vorname', $header, true);
// name / nachname
$lastNameIndex = array_search('name', $header, true);
if($lastNameIndex === false) $lastNameIndex = array_search('nachname', $header, true);
// anrede
$anredeIndex = array_search('anrede', $header, true);
// street
$streetIndex = array_search('straße', $header, true);
// Hausnummer
$hausnummerIndex = array_search('hausnummer', $header, true);
// Telefon
$telefonIndex = array_search('telefon', $header, true);
// PLZ
$plzIndex = array_search('plz', $header, true);
// ORT
$ortIndex = array_search('ort', $header, true);
$anrede = $row[$anredeIndex];
$firstName = $row[$firstNameIndex];
$lastName = $row[$lastNameIndex];
$street = $row[$streetIndex];
$houseNumber = $row[$hausnummerIndex];
$telefon = $row[$telefonIndex];
$plz = $row[$plzIndex];
$ort = $row[$ortIndex];
$title = 'unbekannt';
$geburtsdatum = 0;
$hnr_zusatz = "";
$timestamp = time();
$sql = <<<EOSQL
INSERT INTO adressen (anrede, vorname, nachname, strasse, hnr, telefon1, id_lieferung, priv_gew,
status, titel, geburtsdatum, hnr_zusatz, plz, ort, telefon2, mail, sperrung, sperrgrund, optin,
optindat, timestamp, zusatz1) VALUES ("$anrede", "$firstName", "$lastName", "$street",
"$houseNumber", "$telefon", 0, 0, 0, "$title", $geburtsdatum, "$hnr_zusatz", "$plz", "$ort", 0, "",
0, 0, 0, 0, $timestamp, 0);
EOSQL;
if (!$conn->query($sql) === TRUE) {
echo "Error: cant add this row " . $sql . "<br/>" . $conn->error;
print_r($row);
echo "___________________<br/>";
}
}
I know this isn't safe at all and I am open for sql injections but I will change that after this. Thank you in advance.

Warning Invalid Argument for foreach()

Ok, I have recently purchased a wordpress plugin called WPArcade but, I've been having some issues. In particular I can not get my games to feed like their suppose to. When I attempt to feed games from say, Kongregate, it says 0 games found but also gives me this error:
Warning: Invalid argument supplied for foreach() in C:\Program Files (x86)\Ampps\www\wp\wp-content\plugins\wparcade-plugin\feeds\kongregate\kongregate.php on line 113
I am testing the site on a local server which is why it is in the C Drive.
Kongregates feed: http://www.kongregate.com/games_for_your_site.xml
This is occurring with every publisher in the plugin except for one which doesn't throw me the warning.
Lines 113 through 155: Kongregate
$xml = simplexml_load_string($get_kongregate_feed);
foreach($xml->game as $game) {
$id = intval($game->id);
$name = mysql_real_escape_string($game->title);
$check_id = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."wparcade_kongregate_games WHERE id = '$id'");
$count = mysql_result(mysql_query("SELECT COUNT(*) as newgames FROM ".$wpdb->prefix."wparcade_kongregate_games WHERE id = '$check_id'"),0);
if($count !== '1') {
$name = mysql_real_escape_string($game->title);
$slug = mysql_real_escape_string($game->title);
$slug = wparcade_stringforslug($slug);
$category = mysql_real_escape_string($game->category);
$category = wparcade_strstr_before($category, " & ");
if(!$category) $category = mysql_real_escape_string($game->category);
$categories = mysql_real_escape_string($game->category);
$categories = str_replace(' & ', ', ', $categories);
if(!$categories) $categories = mysql_real_escape_string($game->category);
$description = mysql_real_escape_string($game->description);
$instructions = mysql_real_escape_string($game->instructions);
$thumbnail_url = mysql_real_escape_string($game->thumbnail);
$swf_url = mysql_real_escape_string($game->flash_file);
$width = $game->width;
$height = $game->height;
$tags = strtolower($categories);
$author = mysql_real_escape_string($game->developer_name);
$wparcade_kongregate_feed_game_status = $options['kongregate_feed_game_status'];
$status = $wparcade_kongregate_feed_game_status;
$feedsinglecat_id = $options['kongregate_feed_single_cat'];
$feedcategory = get_cat_name($feedsinglecat_id);
if($feedsinglecat_id !== 'none') {
$categories = $feedcategory;
$category = $feedcategory;
}
$sql = "INSERT INTO ".$wpdb->prefix."wparcade_kongregate_games (id, name, slug, description, thumbnail_url, swf_url, width, height, author, categories, category, tags, instructions, status) VALUES ('$id', '$name', '$slug', '$description', '$thumbnail_url', '$swf_url', '$width', '$height', '$author', '$categories', '$category', '$tags', '$instructions', '$status')";
$list .= '<li class="wparcade_new_games""><strong>'.$name.'</strong></li>';
$wpdb->query($sql);
$inserted++;
} else {
$list .= '<li class="wparcade_old_games"><strong>'.$name.'</strong></li>';
}
}
Just in case, this is the code from the only feed that is working:
$xml = simplexml_load_string($get_scirra_feed);
foreach($xml->game as $game) {
$id = intval($game->gameid);
$name = mysql_real_escape_string($game->name);
$count = mysql_result(mysql_query("SELECT COUNT(*) as newgames FROM ".$wpdb->prefix."wparcade_scirra_games WHERE id = '$id'"),0);
$category = mysql_real_escape_string($game->category);
$slug = mysql_real_escape_string($game->name);
$slug = wparcade_stringforslug($slug);
$check_for = $wpdb->get_var("SELECT name FROM ".$wpdb->prefix."wparcade_scirra_games WHERE slug = '$slug'");
if($count !== '1' && $category !== 'Example' && !$check_for) {
$name = mysql_real_escape_string($game->name);
$slug = mysql_real_escape_string($game->name);
$slug = wparcade_stringforslug($slug);
$category = mysql_real_escape_string($game->category);
$category = str_replace('Shooter', 'Shooting', $category);
$category = str_replace('Defence', 'Defense', $category);
$category = str_replace('Puzzle', 'Puzzles', $category);
$category = str_replace('Rotary', 'Arcade, Rotary', $category);
$categories = $category;
$description = strip_tags(mysql_real_escape_string($game->description));
$instructions = strip_tags(mysql_real_escape_string($game->instructions));
$thumbnail_url = $game->images->small;
$thumbnail_large_url = $game->images->medium;
$screen1_url = $game->images->big;
$embed_url = mysql_real_escape_string($game->embedurl);
$embed_url = str_replace('http://', '//', $embed_url);
$embed_url = str_replace('//', 'http://', $embed_url);
$width = $game->width;
$height = $game->height;
$tags = strtolower($categories);
$author = mysql_real_escape_string($game->author->username);
$wparcade_scirra_feed_game_status = $options['scirra_feed_game_status'];
$status = $wparcade_scirra_feed_game_status;
$feedsinglecat_id = $options['scirra_feed_single_cat'];
$feedcategory = get_cat_name($feedsinglecat_id);
if($feedsinglecat_id !== 'none') {
$categories = $feedcategory;
$category = $feedcategory;
}
$sql = "INSERT INTO ".$wpdb->prefix."wparcade_scirra_games (id, name, slug, description, thumbnail_url, thumbnail_large_url, screen1_url, embed_url, width, height, author, categories, category, tags, instructions, status) VALUES ('$id', '$name', '$slug', '$description','$thumbnail_url', '$thumbnail_large_url', '$screen1_url', '$embed_url', '$width', '$height', '$author', '$categories', '$category', '$tags', '$instructions', '$status')";
$list .= '<li class="wparcade_new_games""><strong>'.$name.'</strong></li>';
$wpdb->query($sql);
$inserted++;
} else {
$list .= '<li class="wparcade_old_games"><strong>'.$name.'</strong></li>';
}
}
Thank you for any help in advance.
P.S. I asked on the plugin's support site but it's been almost a week with no answer.
The issue here is that for Kongregate $xml->game isn't an iterateable object (like an array). The simplest way to debug this is on line 113 try inserting something like:
print_r($xml->game);
//or
print_r($xml);
Getting data visibility into what is and isn't working will probably help you better understand why this isn't working. Good luck!

mysqli_query insert and update within array not working

Hey everyone I am trying to run two insert statements and than finally run an update statement within a php array but it seems not to be working correctly. I realize this code has some problems for instance escaping html data before inserting it into the database isn't ideal however i will fix that later the only thing I am concerned about is the insert and update statements. The following is the code I am using:
This is the job data array being built.
if(empty($_POST) === false && empty($errors) === true){
date_default_timezone_set('America/Denver');
$datetime =date("Y-m-d H:i:s");
$submissionId = rand(10000,99999);
$req_data = array(
'itemId' => $i_san,
'itemName' => $_POST['itemName'],
'submissionId' => $submissionId,
'username' => $_SESSION['username'],
'email' => $_SESSION['email'],
'subDate' => $datetime,
'wistiaId' => $_SESSION['wistiaId']
);
add_DCRequests($req_data);//INSERT INTO `DCrequests`
// === Sanatize inputs === //
$text_1_raw = $_POST['textOne'];
$text_1_noQuotes = str_replace('"',"'",$text_1_raw);
//$text_one = utf8_encode("Ñ");
$text_one = htmlentities(trim($text_1_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_2_raw = $_POST['textTwo'];
$text_2_noQuotes = str_replace('"',"'",$text_2_raw);
$text_two = htmlentities(trim($text_2_noQuotes) , ENT_QUOTES , 'UTF-8' );
$text_3_raw = $_POST['textThree'];
$text_3_noQuotes = str_replace('"',"'",$text_3_raw);
$text_three = htmlentities(trim($text_3_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_4_raw = $_POST['textFour'];
$text_4_noQuotes = str_replace('"',"'",$text_4_raw);
$text_four = htmlentities(trim($text_4_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_5_raw = $_POST['textFive'];
$text_5_noQuotes = str_replace('"',"'",$text_5_raw);
$text_five = htmlentities(trim($text_5_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_6_raw = $_POST['textSix'];
$text_6_noQuotes = str_replace('"',"'",$text_6_raw);
$text_six = htmlentities(trim($text_6_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_7_raw = $_POST['textSeven'];
$text_7_noQuotes = str_replace('"',"'",$text_7_raw);
$text_seven = htmlentities(trim($text_7_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_8_raw = $_POST['textEight'];
$text_8_noQuotes = str_replace('"',"'",$text_8_raw);
$text_eight = htmlentities(trim($text_8_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_9_raw = $_POST['textNine'];
$text_9_noQuotes = str_replace('"',"'",$text_9_raw);
$text_nine = htmlentities(trim($text_9_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_10_raw = $_POST['textTen'];
$text_10_noQuotes = str_replace('"',"'",$text_10_raw);
$text_ten = htmlentities(trim($text_10_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_11_raw = $_POST['textEleven'];
$text_11_noQuotes = str_replace('"',"'",$text_11_raw);
$text_eleven = htmlentities(trim($text_11_noQuotes) , ENT_QUOTES , 'UTF-8');
$text_12_raw = $_POST['textTwelve'];
$text_12_noQuotes = str_replace('"',"'",$text_12_raw);
$text_twelve = htmlentities(trim($text_12_noQuotes) , ENT_QUOTES , 'UTF-8');
$aep = escape_data($_POST['aep']);
$output = escape_data($_POST['output']) . "_" . $_POST['subId'];
$output_scrub = preg_replace('/[^A-Za-z0-9\-_]/', "", $output);
$rendStatus = "ready";
//parse out 3 items from POST target (display shape matrix | disp w | disp h)
$item = escape_data($_POST['target']);
$get_target_w_h = explode('|', $item);
$targ = escape_data($get_target_w_h[0]);
$w = escape_data($get_target_w_h[1]);
$h = escape_data($get_target_w_h[2]);
$matrix = $w ."x". $h;
$BGColor = escape_data($_POST['hex']);
$bg_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $BGColor);
$c1 = escape_data($_POST['hex2']);
$c1_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c1);
$c2 = escape_data($_POST['hex3']);
$c2_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c2);
$c3 = escape_data($_POST['hex4']);
$c3_scrub = preg_replace('/[^A-Za-z0-9\-]/', "", $c3);
// if user is banner attach value = 2
if($_SESSION['userLevel'] == 5){$attach = 2;}else{$attach = 0;}
$show = escape_data($_POST['hide']);
if($show === '1'){
$show_1_val = '{{on}}';
$show_2_val = '{{off}}';
$show_3_val = '{{off}}';
}elseif($show === '2'){
$show_1_val = '{{off}}';
$show_2_val = '{{on}}';
$show_3_val = '{{off}}';
}elseif($show === '3'){
$show_1_val = '{{off}}';
$show_2_val = '{{off}}';
$show_3_val = '{{on}}';
}
$show1_scrub = preg_replace('/[^a-z\{}]/', "", $show1);
$show2 = escape_data($_POST['HideShowLayer2']);
$show2_scrub = preg_replace('/[^a-z\{}]/', "", $show2);
$show3 = escape_data($_POST['HideShowLayer3']);
$show3_scrub = preg_replace('/[^a-z\{}]/', "", $show3);
$still = escape_data($_POST['HideShowLayer1']);
$stillFrame = preg_replace('/[^0-9\.{}]/', "", $custStillFrame);
if($target_file1 != ""){
$image1 = "https://www.test.com/ce/". escape_data($target_file1);}
else{
$image1 = "";
}
if($target_file2 != ""){
$image2 = "https://www.test.com/ce/". escape_data($target_file2);}
else{
$image2 = "";
}
if($target_file3 != ""){
$image3 = "https://www.test.com/ce/". escape_data($target_file3);}
else{
$image3 = "";
}
$completion_date="";
$DCjobsFileId="";
$itemName = escape_data($_POST['itemName']);
$estimatedTime = $currentRendTotal + $custEstRenderTime;
$mydate = date('m/d/Y');
// === Data to insert into the table === //
$job_data = array(
//'bannerToken' => $bannerToken,
'attach' => $attach,
'full-date' => $mydate,
'aep' => $aep,
'target' => $targ,
'output' => $output_scrub,
'itemName' => $itemName,
'render-status' => $rendStatus,
'est_render_time' => $_POST['renderEst'],
'frameNumber' => $stillFrame,
'CustomerName' => $_SESSION['first_name'],
'CustomerEmail' => $_SESSION['email'],
'CustomerKey' => $_SESSION['wistiaId'],
'submissionDate' => $datetime,
'submissionId' => $_POST['subId'],
'itemId' => $custItemId,
'matrix' => $matrix,
'fileformat' => $_POST['format'],
'BGColor' => $bg_scrub,
'ColorOne' => $c1_scrub,
'ColorTwo' => $c2_scrub,
'ColorThree' => $c3_scrub,
'Text-One' => $text_one,
'Text-Two' => $text_two,
'Text-Three' => $text_three,
'Text-Four' => $text_four,
'Text-Five' => $text_five,
'Text-Six' => $text_six,
'Text-Seven' => $text_seven,
'Text-Eight' => $text_eight,
'Text-Nine' => $text_nine,
'Text-Ten' => $text_ten,
'Text-Eleven' => $text_eleven,
'Text-Twelve' => $text_twelve,
'HideShowOne' => $show_1_val,
'HideShowTwo' => $show_2_val,
'HideShowThree' => $show_3_val,
'ImageUploadOne' => $image1,
'ImageUploadTwo' => $image2,
'ImageUploadThree' => $image3,
'completion_date' => "CRAP",
'DCjobsFileId' => "CRAP"
);
add_jobs($job_data);//"INSERT INTO `DCjobs` and INSERT INTO `DCjobsArchive`
header('Content-Type: text/html; charset=utf-8');
header('Location: https://www.test.com/ce/thanks.php?est='.$estimatedTime);
exit();
}elseif(empty($errors) === false){
$reportErrors = "<br /><br /><br />Oops, the following errors occured: <br />" . $errors . "<br /><br /> Please click here to try again. <br /><br />";
}
?>
This is the function that inserts and updates the data from the jobdata array
function add_jobs($job_data){
global $db_conx;
array_walk($job_data, 'array_sanitize');
$jobfields = '`' . implode('`, `', array_keys($job_data)) . '`';
$jobdata = '\'' . implode('\', \'', $job_data) . '\'';
mysqli_query($db_conx, "INSERT INTO `DCjobs` ($jobfields) VALUES ($jobdata)");
mysqli_query($db_conx, "INSERT INTO `DCjobsArchive` ($jobfields) VALUES ($jobdata)");
$selectmaxdcjobsid="SELECT FileRowID, submissionDate FROM DCjobs WHERE submissionDate=(SELECT MAX(submissionDate) FROM DCjobs)";
mysqli_query($db_conx, $selectmaxdcjobsid);
while($row=mysqli_fetch_assoc($selectmaxdcjobsid)){
$maxdcjobsfileid=$row['FileRowID'];
$maxdcjobsubdate=$row['submissionDate'];
}
$selectarchiveid="select submissionId, submissionDate from DCjobsArchive where submissionDate='$maxdcjobsubdate'";
while($row=mysqli_fetch_assoc($selectarchiveid)){
$archivesubmissionid=$row['submissionId'];
$archivesubmissiondate=$row['submissionDate'];
}
$update="UPDATE DCjobsArchive SET DCjobsFileId='$maxdcjobsfileid' WHERE submissionId='$archivesubmissionid'";
mysqli_query($db_conx, $update);
}
It looks like you're trying to get the IDs assigned to the rows that you just inserted, so you can fill in a foreign key. You can do that using the MySQL built-in function LAST_INSERT_ID.
function add_jobs($job_data){
global $db_conx;
array_walk($job_data, 'array_sanitize');
mysqli_query($db_conx, "INSERT INTO `DCjobs` ($jobfields) VALUES ($jobdata)");
mysqli_query($db_conx, "INSERT INTO `DCjobsArchive` (DCjobsFileId, $jobfields) VALUES (LAST_INSERT_ID(), $jobdata)");
}

Categories