SlideShare a Scribd company logo
2
Most read
3
Most read
4
Most read
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
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","")ordie('Couldnotconn
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
//readthejsonfilecontents
$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
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
//convertjsonobjecttophpassociativearray
$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
//gettheemployeedetails
$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
//insertintomysqltable
$sql="INSERTINTOtbl_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
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
//connecttomysqldb
$con=mysql_connect("username","password","")ordie('Couldnotconn
ect:'.mysql_error());
//connecttotheemployeedatabase
mysql_select_db("employee",$con);
//readthejsonfilecontents
$jsondata=file_get_contents('empdetails.json');
//convertjsonobjecttophpassociativearray
$data=json_decode($jsondata,true);
//gettheemployeedetails
$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'];
//insertintomysqltable
$sql="INSERTINTOtbl_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 howto insert JSON data into MySQL using PHP.
Last Modified: Oct-11-2015
6/3/16 How to Insert JSON Data into MySQL using PHP
5/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html
Do you find our tutorials helpful?
Now Like us on Facebook and get notified of our exclusive tutorials.
Hãy là người đầu tiên trong số bạn bè của bạn
thích nội dung này
Kodingmadesimple blogKodingmadesimple blog
410 lượt thích410 lượt thích
Thích Trang Chia sẻ
29ThíchThích Tw eet
Convert Array to JSON and
JSON to Array in PHP |
Example
Get JSON from URL in PHP How to Remove a Property
from an Object in JavaScript
RELATED POSTS
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:xamphtdocslobstersapimonitoring_log.php');
$data = json_decode($jsondata, true);
if (is_array($data)) {
foreach ($data as $row) {
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) {
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.
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" : {
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!!
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')");
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
AvenCarnegie, 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":
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.
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
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",
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:zhtdocsramistestindex.php on line 24
Notice: Undefined index: food_fat in E:zhtdocsramistestindex.php on line 25
Notice: Undefined index: food_bar_code in E:zhtdocsramistestindex.php on line 26
Notice: Undefined index: food_carbs in E:zhtdocsramistestindex.php on line 27
Notice: Undefined index: food_protein in E:zhtdocsramistestindex.php on line 28
Notice: Undefined index: food_servings in E:zhtdocsramistestindex.php on line 29
Notice: Undefined index: points in E:zhtdocsramistestindex.php on line 30
Notice: Undefined index: food_fiber in E:zhtdocsramistestindex.php on line 31
data is updated . . . . !!!
Reply
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
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.
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 | Contact
Designed by AndroidCanv asHQ
Disclosure: This w ebsite uses affiliate 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
Ad

Recommended

Book store Black Book - Dinesh48
Book store Black Book - Dinesh48
Dinesh Jogdand
 
Smart restaurant system (u te m students)
Smart restaurant system (u te m students)
Muhammad Tarmizi
 
Serpentine Pavilion
Serpentine Pavilion
Chandna Doshi
 
Lecture 1 elements of spacemaking
Lecture 1 elements of spacemaking
Abhishek Mewada
 
PPT-Presentation-of-E-Commerce-website-Project.pptx
PPT-Presentation-of-E-Commerce-website-Project.pptx
Himanshu883663
 
Software Application in Quantity Surveying - Report
Software Application in Quantity Surveying - Report
Pang Khai Shuen
 
Online Exam Management System(OEMS)
Online Exam Management System(OEMS)
PUST
 
LOUVRE PYRAMID IN A NUTSHELL
LOUVRE PYRAMID IN A NUTSHELL
shifhana aneezmohamed
 
CodeIgniter L5 email & user agent & security
CodeIgniter L5 email & user agent & security
Mohammad Tahsin Alshalabi
 
Php acak
Php acak
Widiyantoro Lah
 
CodeIgniter L2 helper & libraries & form validation
CodeIgniter L2 helper & libraries & form validation
Mohammad Tahsin Alshalabi
 
CodeIgniter i18n Security Flaw
CodeIgniter i18n Security Flaw
Abbas Naderi
 
CodeIgniter L4 file upload & image manipulation & language
CodeIgniter L4 file upload & image manipulation & language
Mohammad Tahsin Alshalabi
 
File upload for the 21st century
File upload for the 21st century
Jiří Pudil
 
20161029 py con-mysq-lv3
20161029 py con-mysq-lv3
Ivan Ma
 
Yaninis
Yaninis
YANINISMEJIA
 
Hkosc group replication-lecture_lab07
Hkosc group replication-lecture_lab07
Ivan Ma
 
Hardware y software
Hardware y software
Alexi Josue XD
 
Datos personales
Datos personales
Jimmy Bravo
 
Telecom lect 5
Telecom lect 5
Shiraz316
 
Telecollaborative Exchange and Intercultural Education
Telecollaborative Exchange and Intercultural Education
Robert O'Dowd
 
File Upload 2015
File Upload 2015
Choon Keat Chew
 
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
Jairo Hoyos
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Engines
adonatwork
 
Telecom lect 6
Telecom lect 6
Shiraz316
 
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Ernie Souhrada
 
Advanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suite
Kenny Gryp
 
PetroSync - Seismic Interpretation
PetroSync - Seismic Interpretation
PetroSync
 
MySQL Rises with JSON Support
MySQL Rises with JSON Support
Okcan Yasin Saygılı
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQL
Anders Karlsson
 

More Related Content

Viewers also liked (20)

CodeIgniter L5 email & user agent & security
CodeIgniter L5 email & user agent & security
Mohammad Tahsin Alshalabi
 
Php acak
Php acak
Widiyantoro Lah
 
CodeIgniter L2 helper & libraries & form validation
CodeIgniter L2 helper & libraries & form validation
Mohammad Tahsin Alshalabi
 
CodeIgniter i18n Security Flaw
CodeIgniter i18n Security Flaw
Abbas Naderi
 
CodeIgniter L4 file upload & image manipulation & language
CodeIgniter L4 file upload & image manipulation & language
Mohammad Tahsin Alshalabi
 
File upload for the 21st century
File upload for the 21st century
Jiří Pudil
 
20161029 py con-mysq-lv3
20161029 py con-mysq-lv3
Ivan Ma
 
Yaninis
Yaninis
YANINISMEJIA
 
Hkosc group replication-lecture_lab07
Hkosc group replication-lecture_lab07
Ivan Ma
 
Hardware y software
Hardware y software
Alexi Josue XD
 
Datos personales
Datos personales
Jimmy Bravo
 
Telecom lect 5
Telecom lect 5
Shiraz316
 
Telecollaborative Exchange and Intercultural Education
Telecollaborative Exchange and Intercultural Education
Robert O'Dowd
 
File Upload 2015
File Upload 2015
Choon Keat Chew
 
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
Jairo Hoyos
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Engines
adonatwork
 
Telecom lect 6
Telecom lect 6
Shiraz316
 
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Ernie Souhrada
 
Advanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suite
Kenny Gryp
 
PetroSync - Seismic Interpretation
PetroSync - Seismic Interpretation
PetroSync
 
CodeIgniter L5 email & user agent & security
CodeIgniter L5 email & user agent & security
Mohammad Tahsin Alshalabi
 
CodeIgniter L2 helper & libraries & form validation
CodeIgniter L2 helper & libraries & form validation
Mohammad Tahsin Alshalabi
 
CodeIgniter i18n Security Flaw
CodeIgniter i18n Security Flaw
Abbas Naderi
 
CodeIgniter L4 file upload & image manipulation & language
CodeIgniter L4 file upload & image manipulation & language
Mohammad Tahsin Alshalabi
 
File upload for the 21st century
File upload for the 21st century
Jiří Pudil
 
20161029 py con-mysq-lv3
20161029 py con-mysq-lv3
Ivan Ma
 
Hkosc group replication-lecture_lab07
Hkosc group replication-lecture_lab07
Ivan Ma
 
Datos personales
Datos personales
Jimmy Bravo
 
Telecom lect 5
Telecom lect 5
Shiraz316
 
Telecollaborative Exchange and Intercultural Education
Telecollaborative Exchange and Intercultural Education
Robert O'Dowd
 
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
lección 02- creación de Virtual Host laravel 5 + Xampp + Windows
Jairo Hoyos
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Engines
adonatwork
 
Telecom lect 6
Telecom lect 6
Shiraz316
 
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Operational Buddhism: Building Reliable Services From Unreliable Components -...
Ernie Souhrada
 
Advanced Percona XtraDB Cluster in a nutshell... la suite
Advanced Percona XtraDB Cluster in a nutshell... la suite
Kenny Gryp
 
PetroSync - Seismic Interpretation
PetroSync - Seismic Interpretation
PetroSync
 

Similar to How to insert json data into my sql using php (20)

MySQL Rises with JSON Support
MySQL Rises with JSON Support
Okcan Yasin Saygılı
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQL
Anders Karlsson
 
Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
MySQL's JSON Data Type and Document Store
MySQL's JSON Data Type and Document Store
Dave Stokes
 
Data Con LA 2022 - MySQL, JSON & You: Perfect Together
Data Con LA 2022 - MySQL, JSON & You: Perfect Together
Data Con LA
 
Json improvements in my sql 8.0
Json improvements in my sql 8.0
Mysql User Camp
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0
Mydbops
 
Php summary
Php summary
Michelle Darling
 
php databse handling
php databse handling
kunj desai
 
BGOUG15: JSON support in MySQL 5.7
BGOUG15: JSON support in MySQL 5.7
Georgi Kodinov
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
Karwin Software Solutions LLC
 
PHP - Introduction to PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
Vibrant Technologies & Computers
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolment
Rajib Ahmed
 
Php
Php
samirlakhanistb
 
Practical JSON in MySQL 5.7 and Beyond
Practical JSON in MySQL 5.7 and Beyond
Ike Walker
 
lecture 7 - Introduction to MySQL with PHP.pptx
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
Php
Php
khushbulakhani1
 
PHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHP
Vibrant Technologies & Computers
 
Php Tutorial
Php Tutorial
Dr. Ramkumar Lakshminarayanan
 
Ch1(introduction to php)
Ch1(introduction to php)
Chhom Karath
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQL
Anders Karlsson
 
Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
MySQL's JSON Data Type and Document Store
MySQL's JSON Data Type and Document Store
Dave Stokes
 
Data Con LA 2022 - MySQL, JSON & You: Perfect Together
Data Con LA 2022 - MySQL, JSON & You: Perfect Together
Data Con LA
 
Json improvements in my sql 8.0
Json improvements in my sql 8.0
Mysql User Camp
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0
Mydbops
 
php databse handling
php databse handling
kunj desai
 
BGOUG15: JSON support in MySQL 5.7
BGOUG15: JSON support in MySQL 5.7
Georgi Kodinov
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolment
Rajib Ahmed
 
Practical JSON in MySQL 5.7 and Beyond
Practical JSON in MySQL 5.7 and Beyond
Ike Walker
 
lecture 7 - Introduction to MySQL with PHP.pptx
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
Ch1(introduction to php)
Ch1(introduction to php)
Chhom Karath
 
Ad

Recently uploaded (20)

COMPUTER ETHICS AND CRIME.......................................................
COMPUTER ETHICS AND CRIME.......................................................
FOOLKUMARI
 
Topic 1 Foundational IT Infrastructure_.pptx
Topic 1 Foundational IT Infrastructure_.pptx
oneillp100
 
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
taqyed
 
Global Networking Trends, presented at the India ISP Conclave 2025
Global Networking Trends, presented at the India ISP Conclave 2025
APNIC
 
TCP/IP presentation SET2- Information Systems
TCP/IP presentation SET2- Information Systems
agnesegtcagliero
 
cybercrime investigation and digital forensics
cybercrime investigation and digital forensics
goverdhankumar137300
 
BitRecover OST to PST Converter Software
BitRecover OST to PST Converter Software
antoniogosling01
 
Slides: Eco Economic Epochs for The World Game (s) pdf
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
Make DDoS expensive for the threat actors
Make DDoS expensive for the threat actors
APNIC
 
ChatGPT_and_Its_Uses_Presentationss.pptx
ChatGPT_and_Its_Uses_Presentationss.pptx
Neha Prakash
 
Paper: The World Game (s) Great Redesign.pdf
Paper: The World Game (s) Great Redesign.pdf
Steven McGee
 
NOC Services for maintaining network as MSA.ppt
NOC Services for maintaining network as MSA.ppt
ankurnagar22
 
Dark Web Presentation - 1.pdf about internet which will help you to get to kn...
Dark Web Presentation - 1.pdf about internet which will help you to get to kn...
ragnaralpha7199
 
Pitch PitchPitchPitchPitchPitchPitch.pptx
Pitch PitchPitchPitchPitchPitchPitch.pptx
157551
 
Top Mobile App Development Trends Shaping the Future
Top Mobile App Development Trends Shaping the Future
ChicMic Studios
 
Lecture 3.1 Analysing the Global Business Environment .pptx
Lecture 3.1 Analysing the Global Business Environment .pptx
shofalbsb
 
DDoS in India, presented at INNOG 8 by Dave Phelan
DDoS in India, presented at INNOG 8 by Dave Phelan
APNIC
 
ChatGPT A.I. Powered Chatbot and Popularization.pdf
ChatGPT A.I. Powered Chatbot and Popularization.pdf
StanleySamson1
 
最新版加拿大奎斯特大学毕业证(QUC毕业证书)原版定制
最新版加拿大奎斯特大学毕业证(QUC毕业证书)原版定制
taqyed
 
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
AhmadAli716831
 
COMPUTER ETHICS AND CRIME.......................................................
COMPUTER ETHICS AND CRIME.......................................................
FOOLKUMARI
 
Topic 1 Foundational IT Infrastructure_.pptx
Topic 1 Foundational IT Infrastructure_.pptx
oneillp100
 
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
taqyed
 
Global Networking Trends, presented at the India ISP Conclave 2025
Global Networking Trends, presented at the India ISP Conclave 2025
APNIC
 
TCP/IP presentation SET2- Information Systems
TCP/IP presentation SET2- Information Systems
agnesegtcagliero
 
cybercrime investigation and digital forensics
cybercrime investigation and digital forensics
goverdhankumar137300
 
BitRecover OST to PST Converter Software
BitRecover OST to PST Converter Software
antoniogosling01
 
Slides: Eco Economic Epochs for The World Game (s) pdf
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
Make DDoS expensive for the threat actors
Make DDoS expensive for the threat actors
APNIC
 
ChatGPT_and_Its_Uses_Presentationss.pptx
ChatGPT_and_Its_Uses_Presentationss.pptx
Neha Prakash
 
Paper: The World Game (s) Great Redesign.pdf
Paper: The World Game (s) Great Redesign.pdf
Steven McGee
 
NOC Services for maintaining network as MSA.ppt
NOC Services for maintaining network as MSA.ppt
ankurnagar22
 
Dark Web Presentation - 1.pdf about internet which will help you to get to kn...
Dark Web Presentation - 1.pdf about internet which will help you to get to kn...
ragnaralpha7199
 
Pitch PitchPitchPitchPitchPitchPitch.pptx
Pitch PitchPitchPitchPitchPitchPitch.pptx
157551
 
Top Mobile App Development Trends Shaping the Future
Top Mobile App Development Trends Shaping the Future
ChicMic Studios
 
Lecture 3.1 Analysing the Global Business Environment .pptx
Lecture 3.1 Analysing the Global Business Environment .pptx
shofalbsb
 
DDoS in India, presented at INNOG 8 by Dave Phelan
DDoS in India, presented at INNOG 8 by Dave Phelan
APNIC
 
ChatGPT A.I. Powered Chatbot and Popularization.pdf
ChatGPT A.I. Powered Chatbot and Popularization.pdf
StanleySamson1
 
最新版加拿大奎斯特大学毕业证(QUC毕业证书)原版定制
最新版加拿大奎斯特大学毕业证(QUC毕业证书)原版定制
taqyed
 
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
PROCESS FOR CREATION OF BUSINESS PARTNER IN SAP
AhmadAli716831
 
Ad

How to insert json data into my sql using php

  • 1. 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
  • 2. 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","")ordie('Couldnotconn 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 //readthejsonfilecontents $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
  • 3. 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 //convertjsonobjecttophpassociativearray $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 //gettheemployeedetails $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 //insertintomysqltable $sql="INSERTINTOtbl_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
  • 4. 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 //connecttomysqldb $con=mysql_connect("username","password","")ordie('Couldnotconn ect:'.mysql_error()); //connecttotheemployeedatabase mysql_select_db("employee",$con); //readthejsonfilecontents $jsondata=file_get_contents('empdetails.json'); //convertjsonobjecttophpassociativearray $data=json_decode($jsondata,true); //gettheemployeedetails $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']; //insertintomysqltable $sql="INSERTINTOtbl_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 howto insert JSON data into MySQL using PHP. Last Modified: Oct-11-2015
  • 5. 6/3/16 How to Insert JSON Data into MySQL using PHP 5/19www.kodingmadesimple.com/2014/12/how-to-insert-json-data-into-mysql-php.html Do you find our tutorials helpful? Now Like us on Facebook and get notified of our exclusive tutorials. Hãy là người đầu tiên trong số bạn bè của bạn thích nội dung này Kodingmadesimple blogKodingmadesimple blog 410 lượt thích410 lượt thích Thích Trang Chia sẻ 29ThíchThích Tw eet Convert Array to JSON and JSON to Array in PHP | Example Get JSON from URL in PHP How to Remove a Property from an Object in JavaScript RELATED POSTS
  • 6. 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:xamphtdocslobstersapimonitoring_log.php'); $data = json_decode($jsondata, true); if (is_array($data)) { foreach ($data as $row) {
  • 7. 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) {
  • 8. 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.
  • 9. 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" : {
  • 10. 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!!
  • 11. 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')");
  • 12. 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 AvenCarnegie, 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":
  • 13. 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.
  • 14. 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
  • 15. 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",
  • 16. 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:zhtdocsramistestindex.php on line 24 Notice: Undefined index: food_fat in E:zhtdocsramistestindex.php on line 25 Notice: Undefined index: food_bar_code in E:zhtdocsramistestindex.php on line 26 Notice: Undefined index: food_carbs in E:zhtdocsramistestindex.php on line 27 Notice: Undefined index: food_protein in E:zhtdocsramistestindex.php on line 28 Notice: Undefined index: food_servings in E:zhtdocsramistestindex.php on line 29 Notice: Undefined index: points in E:zhtdocsramistestindex.php on line 30 Notice: Undefined index: food_fiber in E:zhtdocsramistestindex.php on line 31 data is updated . . . . !!! Reply
  • 17. 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
  • 18. 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.
  • 19. 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 | Contact Designed by AndroidCanv asHQ Disclosure: This w ebsite uses affiliate 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