-4

I want to insert a json object value in mysql database using php. The object is:

{"data":[{"code":"1234",name:"nike"},{"code":"1034",name:"relexo"}]}.

The database table name is product and the fields name are code and name. How to insert this?

4
  • What have you tried? StackOverflow is a site to help with code, not write code for you. Check out some other examples. Commented Oct 19, 2016 at 5:28
  • @T.J.Crowder this is JSON, he just didn't surround it in quotation marks Commented Oct 19, 2016 at 6:59
  • @Luuk: The above is not what I commented on. Commented Oct 19, 2016 at 7:26
  • @T.J.Crowder ah yes, sorry, missunderstanding on my side Commented Oct 19, 2016 at 7:28

1 Answer 1

-2

quick explination on how you could read a JSON file and append it to a table in the database:

<?php
     //connect to DB
     $con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
    mysql_select_db("product", $con);

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

    //convert json object to php associative array
    $data = json_decode($jsondata, true);

    //get the product details
    $code = $data[code];
    $name = $data[name];

    //insert into mysql table
    $sql = "INSERT INTO product(code, name) VALUES('$code', $name)"
    if(!mysql_query($sql,$con))
    {
       die('Error : ' . mysql_error());
    }

?>

this should be enough to get you going

Sign up to request clarification or add additional context in comments.

2 Comments

mysql_ is deprecated, you should use PDO with prepared statements, that also takes care of the sql injection issue with this code.
true, I've also been using PDO for my projects, but I find sql a good starting point for beginners to learn about database connections, even though it's not good practice, I should've noted this in my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.