How to create a dynamic JSON file by fetching data from localserver database ?
JSON stands for JavaScript Object Notation and is a structured format used for storing and transporting data. It acts as an interface between a server and a web page. It is a lightweight data-interchange format. It is language independent and easy to understand. It is derived from Javascript. JSON objects can be converted to javascript objects and vice-versa using functions like stringify() and parse().
Here, before going through the program, we need to create a MySQL database in our localhost server. PHP is used to connect with the localhost server and to fetch the data from the database table present in our localhost server by evaluating the MySQL queries. Wampserver helps to start Apache and MySQL and connect them with the PHP file. In our PHP code, we are going to make an array of data fetched from the database and then convert them into JSON. A dynamic JSON file will be created to store the array of JSON objects.
Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails.json by converting them into an array of JSON objects.
Creating Database:
Example:
<?php
$user = 'root' ;
$password = '' ;
$database = 'gfg' ;
$servername = 'localhost:3308' ;
$mysqli = new mysqli( $servername ,
$user , $password , $database );
if ( $mysqli ->connect_error) {
die ( 'Connect Error (' .
$mysqli ->connect_errno . ') ' .
$mysqli ->connect_error);
}
$sql2 = "SELECT * FROM userdata" ;
$result = $mysqli ->query( $sql2 );
while ( $row = $result ->fetch_array()) {
$studentdata [] = array (
"GFG_User_Name" => $row [ "username" ],
"No_Of_Problems" => $row [ "problems" ],
"Total_Score" => $row [ "score" ],
"Articles" => $row [ "articles" ],
);
}
$file = "gfguserdetails.json" ;
if ( file_put_contents ( $file ,
json_encode( $studentdata )))
echo ( "File created" );
else
echo ( "Failed" );
$mysqli ->close();
?>
|
Output:
The dynamic JSON file created after running the code on the browser:
Last Updated :
22 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...