0

i have .json file [categories.json]

like this

{
    "apple": [
        "fruit",
        "15"
    ],
    "cat": [
        "animal",
        "400"
    ],
    "pumpkin": [
        "vegetables",
        "20"
    ],
    "orange": [
        "fruit",
        "30"
    ]
}

i want to insert json object into mysql using loop php like this

|___id__|___ product__|_____type_____|__price__|
|   1   |     apple   |    fruit     |    15   |
|   2   |     cat     |    animal    |    400  |
|   3   |   pumpkin   |  vegetables  |    20   |
|   4   |    orange   |    fruit     |    30   |

how can i do thank you

2 Answers 2

2
 $file = 'www.mysite.com/categories.json';
 $data = json_decode(file_get_contents($file), true);

foreach($data as $product => $row){
$sql = "INSERT INTO product ";
  $sql .= "SET product='".mysql_real_escape_string($product)."',type='".mysql_real_escape_string($row[0])."',price=".mysql_real_escape_string($row[1]);
mysql_query($sql);
} // hoping your id field in db is auto_increment
Sign up to request clarification or add additional context in comments.

5 Comments

Danger: You are vulnerable to SQL injection attacks that you need to defend yourself from.
@quentin yes. I just tried to give a simple answer so that he understand better .. May be he will implement with all those check in PDO or mysqli
in this line $file = 'var/www/somefile.json'; my file location is www.mysite.com/categories.json , then i write $file = 'var/www/categories.json'; but not work (not insert) how can i do ?
use www.mysite.com/categories.json as your path to file_get_content that should work
are you using mysqli or mysql ?
1

just use json_decode to convert your Json file into a an array and then loop and insert as you'd do that with an array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.