Create Convert MySQL database data to JSON in PHP

How to Change MySQL tables records data values directly into JSON format to generate JSON data using json_encode() function.

Full form of JSON is JavaScript Object Notation. JSON is mostly used to send data between web server to mobile phones. It converts the normal data into much more lighter significant format which can be easily accessible from android mobile phones via parsing process. So in this tutorial we are simply changing the MySQL database rows, columns data into JSON form using PHP scripting language. This PHP script will automatically converts all data associated with single table at a time and convert its whole records( No limit specified ) into JSON format. So here is the complete step by step tutorial for Create Convert MySQL database data to JSON in PHP.

android-project-download-code-button

Note : We are using json_encode() method to convert all MySQL data into JSON.

 

Create Convert MySQL database data to JSON in PHP

How to Create Convert MySQL database data to JSON in PHP.

Code for Jsondata.php file.

 <?php
include 'DataBaseConfig.php';

//Define your table name here in which you want to retrieve data to convert into JSON.
$sql = "SELECT * FROM page_data";

$result = $conn->query($sql);

if ($result->num_rows >0) {
 // output data of each row
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 //This script is designed by Android-Examples.com
 
 }
 
} else {
 echo "0 results";
}
 echo $json;
$conn->close();

 //This script is designed by Android-Examples.com

?>

Code for DataBaseConfig.php file.

<?php

 //This script is designed by Android-Examples.com
//Define your host here.
$hostname = "localhost";

//Define your database username here.
$username = "root";

//Define your database password here.
$password = "";

//Define your database name here.
$dbname = "test";

// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
} 

?>

Screenshot:

json-data

Click here to download Create Convert MySQL database data to JSON in PHP project script with source code.

Leave a Reply

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