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:43

I have the same requirement. I just want to print a result object into JSON format so I use the code below. I hope you find something in it.

// Code of Conversion
$query = "SELECT * FROM products;";
$result = mysqli_query($conn , $query);

if ($result) {
echo "</br>"."Results Found";

// Conversion of result object into JSON format
$rows = array();
while($temp = mysqli_fetch_assoc($result)) {
    $rows[] = $temp;
}
echo "</br>" . json_encode($rows);

} else {
    echo "No Results Found";
}
查看更多
看淡一切
3楼-- · 2018-12-31 03:44

http://www.php.net/mysql_query says "mysql_query() returns a resource".

http://www.php.net/json_encode says it can encode any value "except a resource".

You need to iterate through and collect the database results in an array, then json_encode the array.

查看更多
登录 后发表回答