Talking about Php.
Ugly title for a post, really… but I did not find any function to convert the result of a MySQL query directly into JSON notation, so I made my own function.
I really needed it today, so I am sharing it with you. It’s not a everyday use function, but I am sure some of you will find it useful, just like it happened with Sending email with multiple attachments with PHP.
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
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.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.