title: Fetching mysql query to JSON
body: <p>Is there any effective way to generate JSON out of MYSQL query like this?</p>
  
  <pre><code>SELECT * FROM player ORDER BY score DESC LIMIT 10
  </code></pre>
  
  <p>because all I have found is this but for me it seems that there must be some easier way to get around:</p>
  
  <pre><code>function sql2json($query) {
      $data_sql = mysql_query($query) or die("'';//" . mysql_error());// If an error has occurred, 
              //    make the error a js comment so that a javascript error will NOT be invoked
      $json_str = ""; //Init the JSON string.
  
      if($total = mysql_num_rows($data_sql)) { //See if there is anything in the query
          $json_str .= "[\n";
  
          $row_count = 0;    
          while($data = mysql_fetch_assoc($data_sql)) {
              if(count($data) &gt; 1) $json_str .= "{\n";
  
              $count = 0;
              foreach($data as $key =&gt; $value) {
                  //If it is an associative array we want it in the format of "key":"value"
                  if(count($data) &gt; 1) $json_str .= "\"$key\":\"$value\"";
                  else $json_str .= "\"$value\"";
  
                  //Make sure that the last item don't have a ',' (comma)
                  $count++;
                  if($count &lt; count($data)) $json_str .= ",\n";
              }
              $row_count++;
              if(count($data) &gt; 1) $json_str .= "}\n";
  
              //Make sure that the last item don't have a ',' (comma)
              if($row_count &lt; $total) $json_str .= ",\n";
          }
  
          $json_str .= "]\n";
      }
  
      //Replace the '\n's - make it faster - but at the price of bad redability.
      $json_str = str_replace("\n","",$json_str); //Comment this out when you are debugging the script
  
      //Finally, output the data
      return $json_str;
  </code></pre>