What is JSON
- JSON stands for JavaScript Object Notation and subset of JavaScript Programming Language.
- JSON is lightweight data interchange format.
- JSON is language independent and familiar to any programming language including C, C++, JAVA, C#, PHP.
- JSON is "self-describing" and easy to understand.
Most of the social networking application apis like Facebook,twitter, geolocation service providers like google, REST-SOAP API producers and around hundreds of similar technologies/frameworks use JSON as data exchange format.
Structure of JSON - JSON Object: A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Ex:- {"name":"Divya", "Stream":"CS"}
- JSON Array: An ordered list of values. In most languages,this is realized as an array, vector, list, or sequence.
An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
Ex: {"Divya", "CS"}.
Now here, I am explanning that how to fetch data from MySQL database and show in JSON format:
Step 1: Create register table in MySQL database
Step 2: Now write the code in PHP file:
- <?php
- $username="root";
- $password="";
- $hostname = "localhost";
-
- $dbhandle = mysql_connect($hostname, $username, $password)
- or die("Unable to connect to MySQL");
- echo "Connected to MySQL<br>";
-
- $selected = mysql_select_db("abc",$dbhandle)
- or die("Could not select examples");
-
- $result = mysql_query("SELECT * FROM register");
- $json_response = array();
-
- while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
-
- $row_array['Fname'] = $row['Fname'];
-
- array_push($json_response,$row_array);
- }
-
- echo json_encode($json_response);
- ?>
- json_encode() - Returns the JSON representation of a value.
Step 3: The output is: