19
6/3/16 How to Insert JSON Data into MySQL using PHP 1/19 www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html ► SQL Database Tutorial ► PHP MySQL Easy ► PHP and MySQL by Exam Ads by Google How to Convert Data from MySQL to JSON using PHP How to Insert JSON Data into MySQL using PHP Popular Posts

How to insert json data into my sql using php

Embed Size (px)

Citation preview

Page 1: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

1/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Home HTML CSS Bootstrap PHP CodeIgniter jQuery Softwares Laptops & Mobiles

► PHP & MySQL ► Json ► PHP Code ► XML to JsonAds by Google

Posted by Valli Pandy On 12/08/2014

How to Insert JSON Data into MySQL using PHP

Hi, in this PHP TUTORIAL, we'll see How

to insert JSON Data into MySQL

using PHP. Check out its reverse

process of Converting Data from MySQL

to JSON Format in PHP here. Converting

json to mysql using php includes several

steps and you will learn things like how to

read json file, convert json to array and

insert that json array into mysql database

in this tutorial. For those who wonder

what is JSON, let me give a brief

introduction.

JSON file contains information stored in JSON format and has the extension of "*.json". JSON

stands for JavaScript Object Notation and is a light weight data exchange format. Being

less cluttered and more readable than XML, it has become an easy alternative format to store

and exchange data. All modern browsers supports JSON format.

Do you want to know how a JSON file looks like? Well here is the sample.

What is JSON File Format?

Example of a JSON File

Save upto 25% OFF on Laptops,

Desktops & Accessories

Shop on Amazon.com

HOT DEALS

Top 10 Best Android Phones Under 15000 Rs

(June 2016)

Best 3GB RAM Smartphones Under 12000 RS

(May 2016)

Best Gaming Laptops Under 40000 Rs In India

(May 2016)

How to Pretty Print JSON in PHP

How to Write JSON to File in PHP

Trending Now

Enter your email id

Subscribe

Subscribe

Search

► SQL Database Tutorial

► PHP MySQL Easy

► PHP and MySQL by Example

Ads by Google

How to Convert Data from MySQL to JSON

using PHP

How to Insert JSON Data into MySQL using

PHP

Popular Posts

Page 2: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

2/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

As you can see by yourself, the JSON format is very human readable and the above file

contains some employee details. I'm going to use this file as an example for this tutorial and

show you how to insert this JSON object into MySQL database in PHP step by step.

As the first and foremost step we have to connect PHP to the MySQL database in order to

insert JSON data into MySQL DB. For that we use mysql_connect() function to connect

PHP with MySQL.

<?php

$con = mysql_connect("username","password","") or die('Could not conn

ect: ' . mysql_error());

mysql_select_db("employee", $con);

?>

Here "employee" is the MySQL Database name we want to store the JSON object. Learn more

about using mysqli library for php and mysql database connection here.

Next we have to read the JSON file and store its contents to a PHP variable. But how to read

json file in php? Well! PHP supports the function file_get_contents() which will read

an entire file and returns it as a string. Let’s use it to read our JSON file.

<?php

//read the json file contents

$jsondata = file_get_contents('empdetails.json');

Step 1: Connect PHP to MySQL Database

Step 2: Read the JSON file in PHP

PHP CodeIgniter Tutorials for Beginners Step

By Step: Series to Learn From Scratch

How to Create Login Form in CodeIgniter,

MySQL and Twitter Bootstrap

How to Create Simple Registration Form in

CodeIgniter with Email Verification

Create Stylish Bootstrap 3 Social Media Icons

| How-To Guide

Easy Image and File Upload in CodeIgniter

with Validations & Examples

AJAX API

Bootstrap CodeIgniter

css CSV

Font Awesome html

JavaScript jQuery

jQuery Plugin json

MySQL PDF

php XML

Categories

Recommeded Hosting

Page 3: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

3/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

?>

Here "empdetails.json" is the JSON file name we want to read.

The next step for us is to convert json to array. Which is likely we have to convert the JSON

string we got from the above step to PHP associative array. Again we use the PHP json

decode function which decodes JSON string into PHP array.

<?php

//convert json object to php associative array

$data = json_decode($jsondata, true);

?>

The first parameter $jsondata contains the JSON file contents.

The second parameter true will convert the string into php associative array.

Next we have to parse the above JSON array element one by one and store them into PHP

variables.

<?php

//get the employee details

$id = $data['empid'];

$name = $data['personal']['name'];

$gender = $data['personal']['gender'];

$age = $data['personal']['age'];

$streetaddress = $data['personal']['address']['streetaddress'];

$city = $data['personal']['address']['city'];

$state = $data['personal']['address']['state'];

$postalcode = $data['personal']['address']['postalcode'];

$designation = $data['profile']['designation'];

$department = $data['profile']['department'];

?>

Using the above steps, we have extracted all the values from the JSON file. Finally let's insert

the extracted JSON object values into the MySQL table.

<?php

//insert into mysql table

$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddres

s, city, state, postalcode, designation, department)

VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city',

'$state', '$postalcode', '$designation', '$department')";

if(!mysql_query($sql,$con))

Step 3: Convert JSON String into PHP Array

Step 4: Extract the Array Values

Step 5: Insert JSON to MySQL Database with PHP Code

Page 4: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

4/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

{

die('Error : ' . mysql_error());

}

?>

We are done!!! Now we have successfully imported JSON data into MySQL database.

Here is the complete php code snippet I have used to insert JSON to MySQL using PHP.

<?php

//connect to mysql db

$con = mysql_connect("username","password","") or die('Could not conn

ect: ' . mysql_error());

//connect to the employee database

mysql_select_db("employee", $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 employee details

$id = $data['empid'];

$name = $data['personal']['name'];

$gender = $data['personal']['gender'];

$age = $data['personal']['age'];

$streetaddress = $data['personal']['address']['streetaddress'];

$city = $data['personal']['address']['city'];

$state = $data['personal']['address']['state'];

$postalcode = $data['personal']['address']['postalcode'];

$designation = $data['profile']['designation'];

$department = $data['profile']['department'];

//insert into mysql table

$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddres

s, city, state, postalcode, designation, department)

VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city',

'$state', '$postalcode', '$designation', '$department')";

if(!mysql_query($sql,$con))

{

die('Error : ' . mysql_error());

}

?>

Read:

How to Insert Multiple JSON Objects into MySQL in PHP

How to Convert MySQL to JSON Format using PHP

Hope this tutorial helps you to understand how to insert JSON data into MySQL using PHP.

Last Modified: Oct-11-2015

Page 5: How to insert json data into my sql using php
Page 6: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

6/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

How to Insert Multiple JSON

Data into MySQL Database

in PHP

PHP Login and Registration

Script with MySQL Example

PHP Search Engine Script

for MySQL Database using

AJAX

Replies

Reply

44 comments:

Anonymous January 19, 2015 5:44 PM

How do you use this for more than one row of data? Say in the json there are two empid's,

and you want to insert each of them?

Reply

Valli Pandy January 19, 2015 11:30 PM

Hi, just loop through the json array if you have multiple rows like this.

//read the json file contents

$jsondata = file_get_contents('empdetails.json');

//convert json object to php associative array

$data = json_decode($jsondata, true);

foreach($data as $row)

{

//get the employee details

$id = $row['empid'];

...

//insert into db

mysql_query($sql,$con);

}

Umair January 31, 2015 7:42 PM

<?php

include 'include/connect.php';

error_reporting(E_ALL);

$jsondata = file_get_contents('D:\xamp\htdocs\lobstersapi\monitoring_log.php');

$data = json_decode($jsondata, true);

if (is_array($data)) {

foreach ($data as $row) {

Page 7: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

7/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

Reply

$am = $row['item']['am'];

$pm = $row['item']['pm'];

$unit = $row['unit'];

$day = $row['day'];

$userid = $row['userid'];

$sql = "INSERT INTO monitoring_log (unit, am, pm, day, userid)

VALUES ('".$am."', '".$pm."', '".$unit."', '".$day."', '".$userid."')";

mysql_query($sql);

}

}

Reply

Umair February 01, 2015 1:02 AM

but sir still my code is not working. Can you solve my issue

Reply

Valli Pandy February 01, 2015 7:34 PM

Hi Umair, you haven't mentioned what error you are getting with the above code.

But I could see you are trying to run a "*.php" file and get the output. Passing the

exact file path to file_get_contents() won't execute the file.

Instead try using this,

file_get_contents('http://localhost/lobstersapi/monitoring_log.php')

Also make sure your web server is running for this to work.

Hope this helps you :)

Umair February 01, 2015 8:19 PM

still not working.

my json data that i am getting from iphone developer is {

"New item" : {

"PM" : false,

"AM" : false

},

"title" : " Unit 13"

}

and my code is :

<?php

include 'include/connect.php';

error_reporting(E_ALL);

$jsondata = file_get_contents('http://localhost/lobstersapi/monitoring_log.php');

$data = json_decode($jsondata, true);

if (is_array($data)) {

foreach ($data as $row) {

Page 8: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

8/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

Reply

$am = $row['New item']['am'];

$pm = $row['New item']['pm'];

$unit = $row['unit'];

$sql = "INSERT INTO monitoring_log (am, pm, unit)

VALUES ('".$am."', '".$pm."', '".$unit."')";

mysql_query($sql);

}

}

not showing any error.

Reply

Valli Pandy February 02, 2015 9:03 PM

Hi, I could see some inconsistencies in your code. Do you get the json output

properly? Even then, if the output contains single row like this,

{

"New item" : {

"PM" : "false",

"AM" : "false"

},

"title" : " Unit 13"

}

then you should not use foreach loop to parse it. Use the loop only if json output

contains multiple rows that looks something like this,

[{

"New item" : {

"PM" : "false",

"AM" : "false"

},

"title" : " Unit 13"

},

{

"New item" : {

"PM" : "false",

"AM" : "false"

},

"title" : " Unit 14"

}]

Also while retrieving data from json, you should use the exact key attribute like this,

$am = $row['New item']['AM'];

$pm = $row['New item']['PM'];

$unit = $row['title'];

(I could see you are using lower case and wrong key attributes here).

Note: If you don't get error print the values in browser and make sure you get the

desired result.

Page 9: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

9/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

Reply

Replies

Reply

Umair February 03, 2015 8:27 PM

Thank you so much sir

Reply

Anonymous February 27, 2015 2:47 PM

Nice tutorial,

But I want to store JSON data as a JSON into mysql, not the way you have done, then what

are the steps to store and retrieve JSON from mysql using php?

Reply

Valli Pandy February 28, 2015 12:57 AM

Hey! you can store json data in mysql without breaking up into columns. Only

proper escaping of json will protect the db from security risk.

But it's not a proper way to do as it just stores a long length of string and will

restrict mysql's ability to search, sort or index data and processing concurrent

queries.

This thread discusses the topic in more detail

http://stackoverflow.com/questions/20041835/putting-json-string-as-field-data-on-

mysql

Hope this helps :)

Vlad N April 03, 2015 12:43 PM

How can a json from an api be saved into mySQL? For example I have this json coming from

an api http://api.androidhive.info/json/movies.json. How can I save this data into the

database?

Reply

Valli Pandy April 04, 2015 1:22 AM

Hi,

If your json o/p is from remote server like the one you have mentioned

(http://api.androidhive.info/json/movies.json) then pass the complete url like this,

//read json file

$jsondata = file_get_contents('http://api.androidhive.info/json/movies.json');

This should work :)

JT May 25, 2015 4:17 AM

Hi,

I can't send my json data to mysql!! I need help...

$json_data = '[{

"external_urls" : "https://open.spotify.com/artist/2QWIScpFDNxmS6ZEMIUvgm",

"followers" : {

Page 10: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

10/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

"total" : 116986

},

"genres" : "latin alternative",

"id" : "2QWIScpFDNxmS6ZEMIUvgm",

"name" : "Julieta Venegas",

"popularity" : 72,

"type" : "artist",

}]';

//convert to stdclass object

$data = json_decode($json_data, true);

$href = $data['external_urls'];

$followers = $data['followers']['total'];

$genres = $data['genres'];

$id = $data['id'];

$name = $data['name'];

$popularity = $data['popularity'];

$type = $data['type'];

//insert values into mysql database

$sql="INSERT INTO `spotify`(`external_urls`, `followers`, `genres`, `empid`, `empname`,

`popularity`, `type`)

VALUES ('$href', '$followers', '$genres', '$id', '$name', '$popularity', '$type')";

Reply

Valli Pandy May 25, 2015 5:21 AM

Hi, the json you have given is invalid with the comma (,) at the end of the last item

("type" : "artist",). It should be like,

$json_data = '[{

...

"popularity" : 72,

"type" : "artist"

}]';

Also the square brackets [] around json data makes it an array. So you should

iterate through it like this,

foreach ($data as $row) {

$href = $row['external_urls'];

$followers = $row['followers']['total'];

$genres = $row['genres'];

$id = $row['id'];

$name = $row['name'];

$popularity = $row['popularity'];

$type = $row['type'];

//insert values into mysql database

$sql="INSERT INTO `spotify`(`external_urls`, `followers`, `genres`, `empid`,

`empname`, `popularity`, `type`)

VALUES ('$href', '$followers', '$genres', '$id', '$name', '$popularity', '$type')";

}

This should work :)

JT May 25, 2015 5:49 AM

This work..!! :) Thank you so much Valli!!

Page 11: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

11/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Reply

Replies

Valli Pandy May 25, 2015 8:49 PM

Glad it works :)

igron July 13, 2015 6:48 PM

Thank you so much!

I'm new in web-programming and was feeling nervous with one of my first tasks. However

with your help i did a daytask within an hour.

Great!

Reply

Valli Pandy July 13, 2015 7:12 PM

Glad! I could help you...Cheers!!!

Gon July 30, 2015 6:22 AM

Hey valli, great work here, could you help me please?

I try to load a JSON named Business from this website

http://www.yelp.com/dataset_challenge. But give me an error on business_id, can t

load that.

my code is the following:

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "Connected successfully";

}

catch(PDOException $e)

{

echo "Connection failed: " . $e->getMessage();

}

//read the json file contents

$jsondata = file_get_contents('c:\yelp_academic_dataset_business.json');

ini_set('memory_limit', '512M');

//convert json object to php associative array

$data = json_decode($jsondata, true);

//get the employee details

$idBusiness = $data['business_id'];

$name = $data['name'];

$neighborhoods = $data['neighborhoods'];

$full_address = $data['full_address'];

$city = $data['city'];

$state = $data['state'];

$latitude = $data['latitude'];

$longitude = $data['longitude'];

$stars = $data['stars'];

$review_count = $data['review_count'];

$open = $data['open'];

$procedure = $conn -> prepare("INSERT INTO business(business_id, name,

neighborhoods, full_address, city, state, latitude, longitude, stars, review_count,

open)

VALUES('$idBusiness', '$name', '$neighborhoods', '$full_address', '$city', '$state',

'$latitude', '$longitude', '$stars', '$review_count', '$open')");

Page 12: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

12/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

$procedure -> execute(); ?>

Gon July 30, 2015 6:24 AM

Hey valli, great work here, could you help me please?

I try to load a JSON named Business from this website

http://www.yelp.com/dataset_challenge. But give me an error on business_id, can t

load that.

my code is the following:

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "Connected successfully";

}

catch(PDOException $e)

{

echo "Connection failed: " . $e->getMessage();

}

//read the json file contents

$jsondata = file_get_contents('c:\yelp_academic_dataset_business.json');

ini_set('memory_limit', '512M');

//convert json object to php associative array

$data = json_decode($jsondata, true);

//get the employee details

$idBusiness = $data['business_id'];

$name = $data['name'];

$neighborhoods = $data['neighborhoods'];

$full_address = $data['full_address'];

$city = $data['city'];

$state = $data['state'];

$latitude = $data['latitude'];

$longitude = $data['longitude'];

$stars = $data['stars'];

$review_count = $data['review_count'];

$open = $data['open'];

$procedure = $conn -> prepare("INSERT INTO business(business_id, name,

neighborhoods, full_address, city, state, latitude, longitude, stars, review_count,

open)

VALUES('$idBusiness', '$name', '$neighborhoods', '$full_address', '$city', '$state',

'$latitude', '$longitude', '$stars', '$review_count', '$open')");

$procedure -> execute(); ?>

Gon July 30, 2015 6:24 AM

Could you help me? Then after make this work i need to load the field attributes to

a table in my sql named attributes to the fields Designation and value, How could i

do that, if there is so many attributes and i can t call them by your code, like

garage, parking, etc. take a look in the Json named business please.

Here's a example of a line of the JSON.

{"business_id": "fNGIbpazjTRdXgwRY_NIXA", "full_address": "1201 Washington

Ave\nCarnegie, PA 15106", "hours": {}, "open": true, "categories": ["Bars",

"American (Traditional)", "Nightlife", "Lounges", "Restaurants"], "city": "Carnegie",

"review_count": 5, "name": "Rocky's Lounge", "neighborhoods": [], "longitude":

-80.084941599999993, "state": "PA", "stars": 4.0, "latitude": 40.396468800000001,

"attributes": {"Alcohol": "full_bar", "Noise Level": "average", "Music": {"dj": false,

"background_music": true, "karaoke": false, "live": false, "video": false, "jukebox":

false}, "Attire": "casual", "Ambience": {"romantic": false, "intimate": false, "touristy":

Page 13: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

13/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

false, "hipster": false, "divey": false, "classy": false, "trendy": false, "upscale": false,

"casual": false}, "Good for Kids": true, "Wheelchair Accessible": false, "Good For

Dancing": false, "Delivery": false, "Coat Check": false, "Smoking": "no", "Accepts

Credit Cards": true, "Take-out": false, "Price Range": 2, "Outdoor Seating": false,

"Takes Reservations": false, "Waiter Service": true, "Caters": false, "Good For":

{"dessert": false, "latenight": false, "lunch": false, "dinner": false, "brunch": false,

"breakfast": false}, "Parking": {"garage": false, "street": false, "validated": false, "lot":

false, "valet": false}, "Has TV": true, "Good For Groups": true}, "type": "business"}

Thank you :)

Valli Pandy July 31, 2015 11:54 PM

Hi, What error you get? From the json you have given below, the business id

seems to be a string value. Did you set the mysql 'datatype' for the said id field as

varchar or not? Please make sure you use the matching datatypes for the mysql

field attributes.

For the last query,

Your query is not clear and I hope this is what you want to ask.

The given json is a complex nested object and to get the value for the key 'garage'

you should use like this,

$garage = $data['attributes']['parking']['garage'];

If you have queries apart from this, please make it clear.

Cheers.

Anonymous August 13, 2015 7:56 AM

Is it possible to exclude certain lines from going into the database? My json file has

1 array with about 20 items in it. Do I just not write in those specific lines in the php

so it'll ignore them? I know the file is small, just doing this as a learning tool.

Valli Pandy August 15, 2015 3:12 AM

Hi, you can do it by checking on the key value on json records like this,

//convert json object to associative array

$data = json_decode($jsondata, true);

//loop through the array

foreach ($data as $row) {

if ($row['empid'] != '5121') { //replace this with your own filter

//get the employee details

$id = $row['empid'];

....

//insert into mysql table

$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city,

state, postalcode, designation, department)

VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state',

'$postalcode', '$designation', '$department')";

...

}

}

Hope this helps.

Cheers.

Page 14: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

14/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Reply

Replies

Reply

Replies

Reply

KALYO August 24, 2015 3:41 PM

Great post, thanks ;-)

Reply

Valli Pandy August 25, 2015 1:29 AM

Glad you liked it :-)

paijo_jr September 11, 2015 1:21 PM

i will try thanks

Reply

BuxsCorner September 14, 2015 7:39 AM

Hi Vallie,

Hmm what if that was a dynamic JSon result, instead of INSERT syntax to MySQL, possible

to UPDATE syntax, or using PHP with if statement before INSERT-ing ?

Reply

Valli Pandy September 17, 2015 12:21 AM

Hi,

The process is same for dynamic json too, for e.g., you can make an api call and

store the result in a variable and proceed in the same way discussed above.

For your second question, yes you can use the json values with UPDATE query

also. As for using if statement, say you want to insert the values only for 'SALES'

department, then use it like

If ($department == "SALES") {

// Insert into DB

// or process the data as you wish

}

Hope that helps!

Cheers.

Rahul Jain September 15, 2015 9:58 PM

Hi,

I am trying to save the same json as mentioned above but not able to save data in mysql, the

code is working but it is showing empty fields in db.

and I have tried to echo the file contents and it is successful ,but the problem is that if I try to

echo the decoded data then it shows a blank page.

Reply

Page 15: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

15/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

Reply

Valli Pandy September 17, 2015 12:29 AM

Hi! It seems like the json format you are trying is not valid. Please make sure you

haven't missed out quotes or any thing else.

You can check if you are using the right JSON format like this,

http://www.kodingmadesimple.com/2015/04/validate-json-string-php.html

Hope that helps.

Cheers.

Marjorie Lagos October 09, 2015 7:18 AM

Hello , how could I do with my code ?

I need to get the data :

Go dia_0 , dia_1 , dia_2 , dia_3 , dia_4 , dia_5 , dia_6 , dia_7 , DC , PMP and CR .

This is my code .

{ "type" : " FeatureCollection "

"features" : [

{ "Type" : " Feature "

"You properties" :

{

" Id" : "1 "

" dia_0 ": " 0 "

" dia_1 ": " 0 "

" dia_2 ": " 0 "

" dia_3 ": " 0 "

" dia_4 ": " 0 "

" dia_5 ": " 0 "

" dia_6 ": " 0 "

" dia_7 ": " 0 "

"CC" : "0 "

" PMP " , " 0 "

"CR ": " 0 "},

... please help

Reply

libraramis December 09, 2015 7:27 PM

Assalam-o-Alikum !!

i m trying to save data form json to sql by using following steps but i m getting error any help

??

//json file//

{

"error_code": "0",

"message": "success",

"food_items": [

{

"id": "1",

"food_name": "apple",

"food_fat": "10",

"food_bar_code": "25",

"food_carbs": "26",

"food_protein": "20",

Page 16: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

16/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

"food_servings": "125",

"food_points": "2",

"food_fiber": "2"

}

]

}

// php code //

include 'config.php';

echo $jsondata = file_get_contents('document.json');

$data = json_decode($jsondata, true);

//get the employee details

$food_name = $data['food_name'];

$food_fat = $data['food_fat'];

$food_bar_code = $data['food_bar_code'];

$food_carbs = $data['food_carbs'];

$food_protein = $data['food_protein'];

$food_servings = $data['food_servings'];

$food_points = $data['points'];

$food_fiber = $data['food_fiber'];

$addFood = "INSERT INTO food_points (food_name, food_fat, food_bar_code, food_carbs,

food_protein, food_servings, points, food_fiber)

VALUES

('$food_name', '$food_fat', '$food_bar_code', '$food_carbs', '$food_protein', '$food_servings',

'$food_points', '$food_fiber')";

if ($conn->query($addFood)===TRUE)

{

echo "data is updated . . . . !!!";

}

else

{

echo "Error: " . $addFood . "

" . $conn->error;;

}

// getting this error //

Notice: Undefined index: food_name in E:\z\htdocs\ramis\test\index.php on line 24

Notice: Undefined index: food_fat in E:\z\htdocs\ramis\test\index.php on line 25

Notice: Undefined index: food_bar_code in E:\z\htdocs\ramis\test\index.php on line 26

Notice: Undefined index: food_carbs in E:\z\htdocs\ramis\test\index.php on line 27

Notice: Undefined index: food_protein in E:\z\htdocs\ramis\test\index.php on line 28

Notice: Undefined index: food_servings in E:\z\htdocs\ramis\test\index.php on line 29

Notice: Undefined index: points in E:\z\htdocs\ramis\test\index.php on line 30

Notice: Undefined index: food_fiber in E:\z\htdocs\ramis\test\index.php on line 31

data is updated . . . . !!!

Reply

Page 17: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

17/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Reply

Replies

Reply

Valli Pandy December 11, 2015 1:38 AM

Welcome! Accessing your json data like this won't work. The key "food_items": [ ]

itself is representing an array. Note that the square brackets around [] is

considered as array and should be parsed with loop.

Working with json array is clearly described in another tutorial. Please check this

url: http://www.kodingmadesimple.com/2015/10/insert-multiple-json-data-into-

mysql-database-php.html

Let me know if you need any more help.

Cheers.

Unknown February 15, 2016 7:55 PM

Hi!

Thanx everybody for help, it's very useful!

How can I get and decode information from several json files in one php script? The files

have the simmilar structure. Could you transform the script for me?

Reply

Unknown February 15, 2016 7:55 PM

Hi!

Thanx everybody for help, it's very useful!

How can I get and decode information from several json files in one php script? The files

have the simmilar structure. Could you transform the script for me?

Reply

Valli Pandy February 19, 2016 4:52 AM

Hi! Say you have all the json files stored in a directory, you can read through the

files one by one like this.

$jdir = scandir($dirpath);

foreach($jdir as $file)

{

//read the json file contents

$jsondata = file_get_contents($file);

...

}

Cheers:)

Unknown February 25, 2016 12:40 AM

My error is-

PHP Notice: Undefined index: dishes in /Applications/MAMP/htdocs/ionicserver/start.php on

line 26

Page 18: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

18/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Replies

Reply

Replies

Reply

Reply

Unknown March 05, 2016 10:03 PM

I am not able to view the data in phpmyadmin database

its showing data succefully inserted

my code is looks like this

Reply

Shahzad Ahmed March 22, 2016 7:08 AM

Thanks for share!

Reply

Valli Pandy March 26, 2016 3:33 AM

Welcome Ahmed:)

Unknown May 02, 2016 8:46 PM

hello,

I need help please: i have a php file which offer a jsonarray, i need to store this result into a

json file so i can explore it later !

For example for the command file_get_contents !

Any response please :( ?!

Reply

Chaima Bennour May 02, 2016 8:50 PM

Hi,

I need Help please !

I need to store the result provided by my php file (which is a jsonarray) into a json file, so i can

explore it later for example to use the command file_get_contents !

Any response please ?

Reply

Valli Pandy May 09, 2016 2:18 AM

We have an article that discusses the topic in detail. Please check this below link...

http://www.kodingmadesimple.com/2016/05/how-to-write-json-to-file-in-php.html

Cheers.

Page 19: How to insert json data into my sql using php

6/3/16 How to Insert JSON Data into MySQL using PHP

19/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html

Newer Post Older PostHome

Enter your comment...

Comment as: Google Account

PublishPublish PreviewPreview

Create a Link

Links to this post

KodingMadeSimple © 2013-2016 | About | Services | Disclaimer | Privacy Policy | Sitemap | ContactDesigned by AndroidCanv asHQ

Disclosure: This w ebsite uses aff iliate links to Amazon.com & Amazon Associates and other online merchants and receives compensation for referred sales of some or all mentioned products but does

not affect prices of the product. All prices displayed on this site are subject to change w ithout notice. Although w e do our best to keep all links up to date and valid on a daily basis, w e cannot guarantee

the accuracy of links and special offers displayed.

Powered by Blogger