Wednesday, 24 July 2013

Export MYSQL record to JSON Data

In this post I will give you a simple idea to create JSON Data from MYSQL record. Export the MYSQL record to JSON array using PHP. You may notice that top social network websites like Facebook and Twitter providing the option to get user data through API. The result of this request will display the JSON or XML output. We are going to create a similar JSON array from MYSQL database using PHP and MYSQL.
MYSQL create JSON Data Using PHP
You can download the original PHP email with attachment script from below:

First create a MYSQL database
  1. CREATE DATABASE `mysql_to_json` ;
Next we need to create a table in database called user_details to store the data and later we will export this data as JSON array
  1. CREATE TABLE `mysql_to_json`.`user_details` (
  2. `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  3. `date_posted` DATE NOT NULL ,
  4. `name` VARCHAR( 250 ) NOT NULL ,
  5. `email` VARCHAR( 1160 ) NOT NULL ,
  6. `phone` VARCHAR( 24 ) NOT NULL ,
  7. `status` INT NOT NULL
  8. ) ENGINE = MYISAM ;
Next inset some data to the above table.
  1. INSERT INTO `mysql_to_json`.`user_details` (`id`, `date_posted`, `name`, `email`, `phone`, `status`) VALUES
  2. ('', '2013-02-12', 'Prasad', 'admin@webinfopedia.com', '1234567890', '1'),
  3. ('', '2013-02-13', 'webinfopedia', 'info@webinfopedia.com', '1234567890', '1'),
  4. ('', '2013-02-15', 'Jhon', 'jhon@webinfopedia.com', '3678652337', '1'),
  5. ('', '2013-02-17', 'Sam', 'sam@webinfopedia.com', '8433123677', '1'),
  6. ('', '2013-02-17', 'Jim', 'jim@webinfopedia.com', '1907456298', '1'),
  7. ('', '2013-02-20', 'San', 'san@webinfopedia.com', '9944227745', '1'),
  8. ('', '2013-02-22', 'User', 'user@webinfopedia.com', '3678652337', '1'),
  9. ('', '2013-02-26', 'Josep', 'josep@webinfopedia.com', '223456987', '1');
Now our MYSQL database is ready with table and data inside that. Next we need to fetch that data from database and convert it as JSON array. Find the simple PHP code below
  1. //Connect to mysql
  2. $a=mysql_connect('localhost','root');
  3. //Select the database
  4. $b=mysql_select_db('mysql_to_json',$a);
  5. //Table name
  6. $table='user_details';
  7. //
  8. $fet=mysql_query('select id,date_posted,name,email,phone from'.$table);
  9. $json = array();
  10. while($r=mysql_fetch_array($fet)){
  11. $json[] = $r;
  12. }
  13. //Display the JSOn data
  14. echo $json_data=json_encode($json);
Above code will fetch all the data from MYSQL database and stores in a PHP array as JSON Data. Later you can use that to any purpose. Hope this post will help you. Don't forget to make the FREE email subscription for more related stuff from mramiteshphp.blogspotcom in future.

No comments:

Post a Comment