I tried to insert it to MySQL Base but its not work for me, please help to solve this. This is how JSON looks like:
{
"status": 1,
"response": {
"Aviator Goggles": {
"price": 1009,
"quantity": 269
},
"Aviator Sunglasses": {
"price": 460,
"quantity": 187
},
"BIKER CRATE": {
"price": 29,
"quantity": 3569
}
},
"time": 1524852778
}
My php code to parse and insert the data:
<?php
$jsonurl = "https://api.opskins.com/IPricing/GetAllLowestListPrices/v1/?appid=578080&format=json_pretty";
$json = file_get_contents($jsonurl);
$data = json_decode($json, true);
print_r ($data);
mysql_connect("127.0.0.1", "root", "") or die (mysql_error ());
mysql_select_db("pubg") or die(mysql_error());
foreach($data as $item) {
mysql_query("INSERT INTO `c5f` (response, price, quantity)
VALUES ('".$item['response']."','".$item['price']."','".$item['quantity']."')") or die(mysql_error());
}
?>
If you look at the decoded json (print_r($data)
), you will see this:
Array
(
[status] => 1
[response] => Array
(
[Aviator Goggles] => Array
(
[price] => 1009
[quantity] => 269
)
[Aviator Sunglasses] => Array
(
[price] => 460
[quantity] => 187
)
[BIKER CRATE] => Array
(
[price] => 29
[quantity] => 3569
)
)
[time] => 1524852778
)
To do your database insert (I am replicating your mysql calls here but you really should upgrade, at the very least to MySQLI but in my opinion PDO is better and also to using prepared statements), you need to iterate through $data['response']
:
foreach ($data['response'] as $key => $item) {
mysql_query("INSERT INTO `c5f` (response, price, quantity)
VALUES ('$key','{$item['price']}','{$item['quantity']}')") or die(mysql_error());
}
because of your query is like ...VALUES("response")
but your inner text contain "
character
it will go crazy like ...VALUES("{ "price": 460, "quantity": 187 },")
you should escape all inner texts using mysql_real_escape_string function :
"... VALUES ('".mysql_real_escape_string($item['response'])."', ..."
have good time
Use PDO for inserting data into your database; here is some example code:
// Set these to your login data
define('DB_HOST', '127.0.0.1');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'pubg');
// We connect to the database using the values above
$pdo = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
// We tell PDO to report us every error
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Now we prepare a query
$sql = $pdo->prepare('INSERT INTO `c5f` SET `response` = :response, `price` = :price, `quantity` = :quantity;');
// We can use $sql to insert data
$data = $response['data'];
foreach($data as $key => $item)
$sql->execute(array(
':response' => $key,
':price' => $item['price'],
':quantity' => $item['quantity']
));
echo 'Insert: '. htmlentities($key) .' ('. $item['quantity'] .' - '. $item['price'] .')'."
";
}
This will connect to the database, prepare your insert statement and execute it for every dataset.