Open In App
Related Articles

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

Like Article
Save Article
Report issue
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 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 . ') '
// 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
    echo("File created");
// Closing the database

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
Similar Reads