Wednesday, 20 April 2016

Get Multiple JSON Data & Insert into Mysql Database in PHP



In this PHP tutorial I show you how to get json data from file and insert into mysql table. If suppose friends you have lots of data into json formate data, so I have make one simple php script that get data from json file and then after it will insert into database table.




Source Code

 --  
 -- Table structure for table `tbl_employee`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_employee` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `gender` varchar(10) NOT NULL,  
  `designation` varchar(30) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;  
 --  
 -- Dumping data for table `tbl_employee`  
 --  

employee_data.json

 [  
   {  
     "name": "Michael Bruce",  
     "gender": "Male",  
     "designation": "System Architect"  
   },  
   {  
     "name": "Jennifer Winters",  
     "gender": "Female",  
     "designation": "Senior Programmer"  
   },  
   {  
     "name": "Donna Fox",  
     "gender": "Female",  
     "designation": "Office Manager"  
   },  
   {  
     "name": "Howard Hatfield",  
     "gender": "Male",  
     "designation": "Customer Support"  
   }  
 ]  

json_mysql.php

 <?php  
 //json_mysql.php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $filename = "employee_data.json";  
 $data = file_get_contents($filename);  
 $array = json_decode($data, true);  
 foreach($array as $row)  
 {  
      $sql = "INSERT INTO tbl_employee(name, gender, designation) VALUES ('".$row["name"]."', '".$row["gender"]."', '".$row["designation"]."')";       
      mysqli_query($connect, $sql);       
 }  
 echo "Employee Data Inserted";  
 ?>  

1 comment: