Create a JSON string from mysql database

JSON stands for JavaScript Object Notation which is basically a data-interchange format. JSON is used where we want to send data as an object, its either be an array or string. When compared to XML it is easily parsable and mostly used where we need to transfer data.

There are mainly two JSON functions used while dealing with it.

json_encode() and json_decode()

json_encode() -
It returns a string containing the JSON representation of value.

json_decode() -
It takes a JSON encoded string and converts it into a PHP variable. When second parameter to json_decode is set to true it return an array otherwise it returns an object.

Let us create a JSON string from php mysql database.


   $sql="SELECT * FROM articles";
    $res=mysql_query($sql);
    $rows = array();
    
    while($row = mysql_fetch_assoc($res)) {
        $rows[] = $row;
    }
    $jsonString = json_encode($rows);


$jsonString contains the JSON string. Again to get it back as php variable we have to decode it as follows.


   $back = json_decode($jsonString,true);
    
    foreach($back as $records){
      echo "<br />";
      print_r($records);
    }


In above example the second parameter of json_decode() function is set to true. So it decodes the JSON string as an associative array. It decodes the string as an object by default. Skip the second parameter if you want to get the result as an object or set it to false.


The third function of JSON family is json_last_error()
It returns the last error (if any) occurred during the last JSON encoding/decoding. You can read more about it here.
Create a JSON string from mysql database Create a JSON string from mysql database Reviewed by JS Pixels on July 13, 2012 Rating: 5

2 comments:

Altaf Web. Powered by Blogger.