1

The structure of the JSON file (prices.json) is very simple:

{"Item1":63.6,"Item2":145.53,"Item3":12.13..........}

I want this to go to db in this way:

Table (analyst)

Row (id): Auto increment ID,

Row (market_name): Item1,

Row (current_price): 63.6,

And keep doing this over and over and over.

Here is what I've done so far:

//connect to mysql db
$con = mysql_connect("root","secret","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("csgo", $con);

//read the json file contents
$jsondata = file_get_contents('prices.json');

//convert json object to php associative array
$data = json_decode($jsondata, true);
Loleris54
  • 35
  • 5
  • If you're writing new code, **_please_ don't use the `mysql_*` functions**. They are old and broken, were deprecated in PHP 5.5 (which is so old it no longer even receives security updates), and completely removed in PHP 7. Use [`PDO`](https://secure.php.net/manual/en/book.pdo.php) or [`mysqli_*`](https://secure.php.net/manual/en/book.mysqli.php) with _prepared statements_ and _parameter binding_ instead. See http://stackoverflow.com/q/12859942/354577 for details. – ChrisGPT was on strike Jul 01 '17 at 14:23
  • 1
    Is this only going to happen once or is it something that will happen often? Easiest way will be to loop over the array counting as you loop and every 1k or so. – Doug Jul 01 '17 at 14:24
  • i want all the Items to be in new row, and it will happen once. – Loleris54 Jul 01 '17 at 14:28

1 Answers1

0

First step is convert JSON string into PHP Array:

$data = json_decode($jsondata, true);

Second step extract the array values and insert in database:

foreach( $data as $key => $data2 ) {
   $market_name = $key;
   $current_price = $data 
   $sql = "INSERT INTO your_table ('market_name', 'current_price') VALUES ('$market_name', '$current_price')";
   $res = mysqli_query($sql, $con);  
}

You can set your own query.

mshomali
  • 664
  • 1
  • 8
  • 27
  • I get this error: PHP Warning: mysqli_query() expects parameter 1 to be mysqli, string given in / home/jackpot/bot/prices.php on line 18 Error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''market_name', 'c urrent_price') VALUES ('Sticker | Don't Worry, I'm Pro', 'Array' at line 1 – Loleris54 Jul 01 '17 at 15:53
  • correct syntax is `mysqli_query($con, $sql )`. Just swap the parameters of the function. you can insert data from json is from above code and handle the database is your task! – mshomali Jul 01 '17 at 16:18