sql2json() - Converts SQL Results to JSON String

sql2json() converts the result of the given SQL query to its equivalent JSON string.

See Demo

This function will take a SQL query as it argument, execute it, fetch its result and convert it to a JSON string and then return the JSON string. This is very useful if you are creating Ajax applications and decide to use JSON over XML. If you have decided to use XML, take a look at my XML Parser for JavaScript instead.

Example

Query : SELECT user_id,user_name FROM dummy_data_users WHERE user_status='1'
Code : sql2json("SELECT user_id,user_name FROM dummy_data_users WHERE user_status='1'");
JSON :

[
	{"user_id":"1","user_name":"Binny"},
	{"user_id":"2","user_name":"Bill Gates"},
	{"user_id":"3","user_name":"George Bush"},
	{"user_id":"4","user_name":"Secret Agent"}
]

See

Query : SELECT * FROM dummy_data_users WHERE user_id='1'
Code : sql2json("SELECT * FROM dummy_data_users WHERE user_id='1'");
JSON :

[{
	"user_id":"1",
	"user_name":"Binny",
	"user_email":"myfakeemail@nowhere.com",
	"user_site":"http://www.bin-co.com/",
	"user_info":"Hi!",
	"user_status":"1"
}]

See

Code

<?php
//Function will take an SQL query as an argument and format the resulting data as a 
//    json(JavaScript Object Notation) string and return it.
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) > 1$json_str .= "{\n";

            
$count 0;
            foreach(
$data as $key => $value) {
                
//If it is an associative array we want it in the format of "key":"value"
                
if(count($data) > 1$json_str .= "\"$key\":\"$value\"";
                else 
$json_str .= "\"$value\"";

                
//Make sure that the last item don't have a ',' (comma)
                
$count++;
                if(
$count count($data)) $json_str .= ",\n";
            }
            
$row_count++;
            if(
count($data) > 1$json_str .= "}\n";

            
//Make sure that the last item don't have a ',' (comma)
            
if($row_count $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;
}

Comments

Anonymous at 10 Apr, 2008 07:40
this is totally unnecessary just use json_encode on the resulting array
Reply to this.
Binny V A at 11 Apr, 2008 05:30
Thats true - I created this function before json_encode was available. Now its recommend that you use json_encode.
Reply to this.
Kevin at 13 Apr, 2009 04:34
And Anonymous losers who post miserable comments such as the ones above are well errr.... losers. Thank you for your efforts
Reply to this.
Anonymous at 31 Oct, 2008 04:54
You bunch of beginners and college kids don't know anything about programming in real world.
Reply to this.
Flavio at 28 Apr, 2009 12:07
Thank you!
jdon_encode is avaliable in php 5.2 and above. for older vesions this is very useful!
Reply to this.
Flavio at 28 Apr, 2009 12:07
Thank you!
json_encode is avaliable in php 5.2 and above. for older vesions this is very useful!
Reply to this.
Aras at 06 Apr, 2010 12:30
This post was helpful to me, thanks!
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed