[Tutorial] - MySQL to JSON Data Using PHP

Encoding JSON in PHP
Some years ago, JSON support was provided through the json pecl extension. Since PHP 5.2, it is included in the core directly, so if you use a recent PHP version you should have no trouble using it.

Note: If you run an older version of PHP than 5.3, I recommend you to upgrade anyway. PHP 5.3 is the oldest version that is currently supported and with the latest PHP security bugs found I would consider it critical to upgrade as soon as possible.

Step 1: Create file with the naming as index.php

$username = 'root';  //database user name variable
$password ='';       //database password
$host ='localhost';

$databasename = 'json-db';

 $conn = mysql_connect($host, $username, $password);
 if (!$conn)
  die('Could not connect: ' . mysql_error());
//select database name and connect 

 mysql_select_db($databasename, $conn);

 $sth = mysql_query("Select * from users");
 $rows = array();
 while($r = mysql_fetch_assoc($sth)) {
  $rows[] = $r;
 $json = json_encode($rows);
 echo stripslashes($json); 

Step 2: Retrieve JSON data (callback.php)
There are two ways to call data from another file (index.php), using JQuery or PHP (json_decode).

a. Using JQuery

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
$(document).ready(function (){
        //using getJSON
 $.getJSON("http://localhost/path-to-your-file/index.php", function(data){ 
    // do stuff with json (in this case an array)
 //using Ajax
   dataType: 'json', // Notice! JSONP <-- P (lowercase)
    // do stuff with json (in this case an array)

b. Using PHP json_decode()

$url = 'http://localhost/path-to-your-file/index.php';
$json = file_get_contents($url);
$datas = json_decode($json);

foreach($datas as $data){
 echo $data->last_name.'

credited to: http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP


Popular Posts


Back to Top