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.
<?php // 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"); exit(); } //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()) { $dbdata[]=$row; } //Print array in JSON format echo json_encode($dbdata); ?>
Result:
[ { "actor_id":"1", "first_name":"PENELOPE", "last_name":"GUINESS", "last_update":"2006-02-15 04:34:33" }, { "actor_id":"2", "first_name":"NICK", "last_name":"WAHLBERG", "last_update":"2006-02-15 04:34:33" }, { "actor_id":"3", "first_name":"ED", "last_name":"CHASE", "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.