How to generate Json code from Mysql database

In this tutorial I will show a simple way to generate Json code from Mysql database.

I have created a new file on my xampp server and I have connected it to the database:

$db = mysqli_connect("localhost","user2","123456","zend");

Next I will extract data from database:

$mn = mysqli_query($db,"SELECT * FROM album");

I will create a new array:

$jsonval = array();

And I will add data from database in the created array by using this code:

while($get = mysqli_fetch_assoc($mn)):
$json = array();
$json["artist"] = utf8_encode($get["artist"]);
$json["title"] = utf8_encode($get["title"]);
array_push($jsonval,$json); // array_push will add the new array at the end of my created array.

And nowm I will generate the json code from my array:

echo json_encode($jsonval);

Video tutorial:

Leave a Comment