-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?

Erik Terwan
  • 2,710
  • 19
  • 28
  • What have you tried? StackOverflow is a site to help with code, not write code for you. Check out [some](http://stackoverflow.com/questions/34848563/insert-nested-json-array-as-parameter-in-php-mysql-database) [other](http://stackoverflow.com/questions/29937123/insert-json-data-in-mysql-database-with-php) [examples](http://stackoverflow.com/questions/26731046/how-to-insert-json-array-into-mysql-database-with-php). – Erik Terwan Oct 19 '16 at 05:28
  • @T.J.Crowder this is JSON, he just didn't surround it in quotation marks – Grey Oct 19 '16 at 06:59
  • @Luuk: The above is [not what I commented on](http://stackoverflow.com/revisions/40106122/1). – T.J. Crowder Oct 19 '16 at 07:26
  • @T.J.Crowder ah yes, sorry, missunderstanding on my side – Grey Oct 19 '16 at 07:28

1 Answers1

-1

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

Grey
  • 877
  • 9
  • 29
  • `mysql_` is deprecated, you should use [PDO with prepared statements](http://php.net/manual/en/pdo.prepared-statements.php), that also takes care of the sql injection issue with this code. – Erik Terwan Oct 19 '16 at 18:53
  • 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 – Grey Oct 20 '16 at 06:31