PHP Encode and Decode Mysql Data into JSON

JSON (Javascript Object Notation) is one of the most popular and lightweight data-interchange format. It is very easy for machine to parse and for human to read. JSON is a text format which is completely language independent.

JSON is built on two structures:

  • Name/Value Pair : In different languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • Ordered list of values : In most languages, this is realized as an array, vector, list, or sequence

If you want to read more about JSON you can visit json.org

Also Read:

 

PHP JSON:

PHP has json extension with 4 functions which are:

Function Description
json_encode ($value, $options, $depth) It returns the JSON representation of a value.

  • $value: is a value being encoded.
  • $options: bitmask consisting of different values. For more details visit JSON Constants
  • $depth: Set the maximum depth. Must be greater than zero.
json_decode($json, $assoc, $depth, $options) Decodes json string.

  • $json: Json string being decoded. This function will only works with UTF-8 encoded strings
  • $assoc: Optional parameter with boolean values. By default json_decode() return OBJECT. Set this option TRUE to get ARRAY.
  • $depth: User specified recursion depth.
  • $options: Json decode option. Currently it supports 2 option JSON_BIGINT_AS_STRING and JSON_OBJECT_AS_ARRAY
json_last_error_msg() Returns the error of the last json_encode() or json_decode() call.
json_last_error() Returns the last error occurred.

PHP Encode and Decode Mysql Data into JSON

I will use both MYSQLi procedural and object oriented in my example to encode and decode mysql data into json. I will create a demo database with customers table and fetch records.

Create Database:

Create Table:

Insert Records in Table:

MYSQLI Procedural Encode JSON Data:

In the above example I just picked 10 records from customers table and put them in $array array. Then I used json_encode function to convert $array into json.

Output:

MYSQLI Procedural Decode JSON Data:

By default json_decode function decodes json string as an object. If you want to convert json string into array then you have to pass TRUE as a second argument in json_decode function.

JSON decode as an Object:

Output:

JSON decode as an Array:

Output:

MYSQLI Object Oriented Encode JSON Data:

In the above code, I fetched 10 records from customers table and store them in $rows variable. On this point you may be wondering how can I fetch all records without while loop. In mysqli object oriented, there is a function fetch_all() which fetch all the records in given query.

Output:

JSON decode as an Object:

Output:

JSON decode as an Array:

Output:

 

Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *