I did not find any function to convert the result of a MySQL query directly into JSON notation, so I made my own function.
function mysql2json($mysql_result,$name){
$json="{\n\"$name\": [\n";
$field_names = array();
$fields = mysql_num_fields($mysql_result);
for($x=0;$x< $fields;$x++){
$field_name = mysql_fetch_field($mysql_result, $x);
if($field_name){
$field_names[$x]=$field_name->name;
}
}
$rows = mysql_num_rows($mysql_result);
for($x=0;$x< $rows;$x++){
$row = mysql_fetch_array($mysql_result);
$json.="{\n";
for($y=0;$y<count($field_names);$y++) {
$json.="\"$field_names[$y]\" :Â Â Â \"$row[$y]\"";
if($y==count($field_names)-1){
$json.="\n";
}
else{
$json.=",\n";
}
}
if($x==$rows-1){
$json.="\n}\n";
}
else{
$json.="\n},\n";
}
}
$json.="]\n};";
return($json);
}
The first parameter is the result of the query, without any parsing, just the output of mysql_query function, the second parameter is the name you want to give to your JSON object.
Returns a string with the JSON notation of the result.
I did not find any function to convert the result of a MySQL query directly into JSON notation, so I made my own function.
This entry was posted on Friday, October 9th, 2009 at 9:08 am and is filed under PHP, Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
You might also like
| Using URLLoader to send and load Data to Server Used FLEX Here is a very simple example of two way communication with database using Flex and PHP. In this example, we are... | Date Class in AS3 This tutorial will teach you how to use the Date Class in AS3 to retrieve all information related to time (includes... | Compass Effect in AS3 We show how to create a draggable compass in AS3. We use tweening as our primary tool. There is a number of trigonometric... | Applying Flash Filters Using AS3 Filters are readymade effects which you can apply to all visual objects in Flash. This tutorial will teach you... |










how would i integrate this in a php file? just add the db connection?
what i mean, cause i just saw its unclear, this returns $json string…now how do i print this to screen….
and what vars do i have to change in it…sorry, im new to php and json. ive been trying to print the results from a db for hours and cant get it to work, i can however get them into xml format to print…
$name = "test"; $mysql_result = mysql_query("your sql code...."); echo mysql2json($mysql_result,$name);Thank you! Great!
you’re welcome