Thursday, August 15, 2013

Retrieving Data using MYSQL vs JSON




When Dealing with more amount data the most important factor is performance.Below are the two methods which calculate the time  duration of data for display.

When working with more amount data normally we are using MySQL to retrieving and display  data from database, but there is another method to store and retrieve data from database in fast manner which is using “JSON”  file.
Lets see the difference between two methods to store and retrieve the data.
Suppose we have database with 50,000 records.
First of all store the database records  into JSON file.
Store data into JSON file:

  1.  mysql_connect("localhost","root","");
  2.  mysql_select_db("test");
  3.  
  4. $query=mysql_query("SELECT * FROM temp ORDER BY id");
  5.  $arr=array();
  6.  while($k=mysql_fetch_object($query))
  7.  {
  8.  $arr[]=$k;
  9.  }
  10.  
  11. file_put_contents("json.json",json_encode($arr));                                                                

Direct request with MySQL:
  1. mysql_connect("localhost","root","");
  2.  mysql_select_db("test");
  3.  
  4. $query=mysql_query("SELECT * FROM temp ORDER BY id");
  5.  while($k=mysql_fetch_object($query))
  6.  {
  7. echo "<pre>";
  8.  
  9. //  Print the data
  10. print_r($k);
  11.  }


                    Retrieve data using JSON file:




                    1. </pre>
                    2. // Read data from json file
                    3.  
                    4. $str=json_decode(file_get_contents("json.json"));
                    5.  echo "<pre>";
                    6.  foreach($str as $s)
                    7.  {
                    8. print_r($s);
                    9.  }

                    convert mysql data to json :


                    1. <?php

                    2. mysql_connect('localhost','root',' ')or die("cannot connect"); 
                    3. mysql_select_db(fb)or die("cannot select DB");

                    4. $sql="SELECT * FROM users ";
                    5. $result=mysql_query($sql);
                    6. while($rows=mysql_fetch_array($result)){

                    7. echo $p[]= $rows['username'];

                    8. }
                    9. echo json_encode($p);
                    10. ?>






                    No comments:

                    Post a Comment