Location: PHPKode > scripts > MySQL2JSON > mysql2json/MYSQL2JSON.class.php
<?php
class MYSQL2JSON{

	var $num_fields;
	var $root_string;
	
	function MYSQL2JSON(){
		$this->root_string = 'result';
	}
	
	function query($sql){
		
		$result_resource = mysql_query(trim($sql));
		if(!$result_resource) die('MYSQL2JSON - Query Error: '.mysql_error());
		
		$arTableFields = $this->findAllTableFields($result_resource);
		
		$arAllRows = array();
		while($row = mysql_fetch_array($result_resource)){
			$arOneRow = array();
			for($j = 0; $j < $this->num_fields; $j++){
				$data = $this->encode_msg($row[$j]);
				$arOneRow[] = '"'.$arTableFields[$j].'"'.':'.'"'.$data.'"';
			}
			$arAllRows[] = '{'.implode(',', $arOneRow).'}';
		}
		
		if(count($arAllRows) == 1){
			return '{"'.$this->root_string.'": ' . $arAllRows[0] . '}';
		}else{
			return '{"'.$this->root_string.'": ' . '['.implode(',', $arAllRows).']' . '}';
		}
	}
	
	function findAllTableFields($result_resource){
		$fields = array();
		$this->num_fields = mysql_num_fields($result_resource);
		for($i = 0; $i < $this->num_fields; $i++){
			$field_meta = mysql_fetch_field($result_resource);
			$fields[] = $field_meta->name;
		}
		return $fields;
	}
	
	function encode_msg($msg){
		 return utf8_decode(utf8_encode($msg));
	}
}
?>
Return current item: MySQL2JSON