JSON encode MySQL results

2018-12-31 03:02发布

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?

标签: php mysql json
20条回答
闭嘴吧你
2楼-- · 2018-12-31 03:36
$rows = json_decode($mysql_result,true);

as simple as that :-)

查看更多
心情的温度
3楼-- · 2018-12-31 03:37

I solved like this

$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
	$list=array();
	$i=0;
	while ($cresult=$stmt->fetch()){	
				
	
		$list[$i][0]=$cde;
		$list[$i][1]=$v_off;
		$list[$i][2]=$em_nm;
		$list[$i][3]=$q_id;
		$list[$i][4]=$v_m;
		$i=$i+1;
	}
	echo json_encode($list);		
This will be returned to ajax as result set and by using json parse in javascript part like this :

obj = JSON.parse(dataX);

查看更多
柔情千种
4楼-- · 2018-12-31 03:37
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
查看更多
美炸的是我
5楼-- · 2018-12-31 03:38

How to create JSON using data from MySQL database

JSON (JavaScript Object Notation) is more preferred nowadays over XML as it’s lightweight, readable and easily manageable for exchanging data across various platforms. we’ll see how JSON Data can be created from Employee table stored in MySQL database.

 echo json_encode($data);

Live : [Example ]

查看更多
怪性笑人.
6楼-- · 2018-12-31 03:38

For example $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER' ");

1.) if $result is only one row.

$response = mysql_fetch_array($result);
echo json_encode($response);

2.) if $result is more than one row. You need to iterate the rows and save it to an array and return a json with array in it.

$rows = array();
if (mysql_num_rows($result) > 0) {
    while($r = mysql_fetch_assoc($result)) {
       $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
       $rows[$id] = $r; //save the fetched row and add it to the array.
    }
}    
echo json_encode($rows);
查看更多
刘海飞了
7楼-- · 2018-12-31 03:42

Code:

$rows = array();

while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {

 $row_array['result'] = $r;

  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}

echo json_encode($rows);
查看更多
登录 后发表回答