Tuesday, 14 June 2016

Create A JSON File With PHP And MySQL

How to Create a JSON file with PHP and MySQL ?

Step 1: Create “Students” table in MySQL. The name of the database here is “test”.
CREATE TABLE `students` (
  `sno` int(10) NOT NULL auto_increment,
  `rollno` varchar(20) NOT NULL,
  `sname` varchar(100) NOT NULL,
  `class` varchar(100) NOT NULL,
  PRIMARY KEY  (`sno`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
-- 
-- Dumping data for table `students`
-- 
INSERT INTO `students` VALUES (1, 'PHPT20161', 'vikram', '2nd');
INSERT INTO `students` VALUES (2, 'PHPT20162', 'Lucky', 'LKG');
INSERT INTO `students` VALUES (3, 'PHPT20163', 'Dusyanth', '3rd');
INSERT INTO `students` VALUES (4, 'PHPT20165', 'Lucky', '4th');

Step 2: Now, copy and execute the following PHP Code.

include('dbconfig.php');
$sql = "select * from students";
$result = mysqli_query($con,$sql);
$students_data = array();
while($row=mysqli_fetch_assoc($result))
{
$students_data[] = $row;
}
$json = json_encode($students_data);
//append data in json file 
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
?>

Step 3: Copy the dbconfig.php file to access MYSQL DB.
$con = mysqli_connect('localhost','root','','test123'); 
?>

No comments:

Post a Comment