How to convert MYSQL data to JSON using PHP

Many web applications expect external data in JSON format, hence converting MySQL data to JSON is something that web developers encounter on a regular basis. JSON (JavaScript Object Notation) is fast becoming the most popular data format in server/browser communication. It is light weight, human readable and easy to generate and parse.

Data from MySQL database can be easily converted into JSON format using PHP. The below example uses Sakila sample database that comes with standard MySQL installation. It fetches the first 3 rows of actor table into an associative array using mysqli_fetch_assoc(). Then the array is encoded into JSON using json_encode.


// Initialize variable for database credentials
$dbhost = 'hostname';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'sakila';

//Create database connection
  $dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

//Check connection was successful
  if ($dblink->connect_errno) {
     printf("Failed to connect to database");

//Fetch 3 rows from actor table
  $result = $dblink->query("SELECT * FROM actor LIMIT 3");

//Initialize array variable
  $dbdata = array();

//Fetch into associative array
  while ( $row = $result->fetch_assoc())  {

//Print array in JSON format
 echo json_encode($dbdata);


	"last_update":"2006-02-15 04:34:33"
	"last_update":"2006-02-15 04:34:33"
	"last_update":"2006-02-15 04:34:33"

As you can see, the result is a valid JSON. You may use this in combination with Jquery/AJAX to pass database data to a web application that expects data in JSON.

Post a comment


Your Comment

Email (We dont publish it)


Nothing the first to share wisdom.