Open In App

How to create a dynamic JSON file by fetching data from localserver database ?

Improve
Improve
Like Article
Like
Save
Share
Report

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
  
// PHP program to connect with
// localserver database
$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);
}
  
// SQL query to select data
// from database
$sql2 = "SELECT * FROM userdata";
$result = $mysqli->query($sql2);
  
// Fetching data from the database
// and storing in array of objects
while($row = $result->fetch_array()) {
    $studentdata[] = array(
        "GFG_User_Name" => $row["username"],
        "No_Of_Problems" => $row["problems"],
        "Total_Score" => $row["score"],
        "Articles" => $row["articles"],
    );
}
  
// Creating a dynamic JSON file
$file = "gfguserdetails.json";
  
// Converting data into JSON and putting
// into the file
// Checking for its creation
if(file_put_contents($file
        json_encode($studentdata)))
    echo("File created");
else
    echo("Failed");
  
// Closing the database
$mysqli->close();
  
?>


Output:

The dynamic JSON file created after running the code on the browser:



Last Updated : 22 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads