convert-mysql-rows-into-json-format-using-php

convert-php-mysql-to-json-format

convert-php-mysql-to-json-format

When we are dealing with web services, we are received the server side data into the JSON format or other. When it comes at PHP, then transforming the MySQL data to JSON Format becomes very important task for developer. In very less time JSON has gained its popularity over the XML format in terms of exchanging the data between web application as it carries the light weight data and stores the complex data structure in text format. In this post we will see that how to convert MySQL data rows in JSON format in PHP, It is very easy and simple task for any developer.

Convert MySQL to JSON String in PHP

Step 1. We need to establish connectivity between MySql Database and PHP.

    //open connection to mysql db
    $connection = mysqli_connect("localhost","root","","db_members") or die("Error " . mysqli_error($connection));

Step 2: Get required data from MySQL Database

<?php
    //fetch table rows from mysql db
    $sql = "select * from tbl_members";
    $result = mysqli_query($connection, $sql) 
    or die("Error in Selecting " . mysqli_error($connection));
?>

Step 3 : Convert MySQL Result Set to PHP Array

<?php //create an array
    $member_data = array();
    while($row =mysqli_fetch_assoc($result)){
        $member[] = $row;
    }
?>

Step 4: Convert PHP array to JSON String

<?php 
    echo json_encode($member);
?>

Here's the Complete Code:

<?php
    //open connection to mysql db
    $con = mysqli_connect("localhost","root","","db_members") or die("Error " . mysqli_error($connection));
    
    //fetch table rows from mysql db
    $sql = "select * from tbl_members";
    $result = mysqli_query($connection, $sql) 
    or die("Error in Selecting " . mysqli_error($con));
    
    $member_data = array();
    while($row =mysqli_fetch_assoc($result)){
        $member[] = $row;
    }

    echo json_encode($member); 
    
?>
   

If this post is useful for you, please like and share it on social media.

Thanks

 

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *