Home » Programming » Convert Direct MySql to JSON

Convert Direct MySql to JSON

This time we have a function that is directly relevant to the query result Mysql to Json converts, In versions of PHP 5.2+ json_encode function created converting speed with which the work is easier.
Of course, this function is not used, and that can be a good thing to learn more about you and how to create the output Json structure.
Another thing you can also use this method to communicate with Flash ,because ActionScript classes written in different versions.
The accuracy and speed of JSON output is supported.

Direct conversion function Mysql to Json:

 

 

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 code used is simple, you just get more out of your database with a different query to get the result and the structure function properly.

Print Friendly
Tags :
Previous post link
Next post link

About Behrouz Pooladrag

Born: May 27, 1988 Occupation: Adobe Flash, programming and web design, graphic design, multimedia, web-based software

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Scroll To Top