JSON Encode an Entire MySQL Result Set

JSON encode MySQL results

$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);

The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here

NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.

Json encode an entire mysql result set

If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:

$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);

How to convert result table to JSON array in MySQL

New solution:

Built using Your great comments, thanks!

SELECT JSON_ARRAYAGG(JSON_OBJECT('name', name, 'phone', phone)) from Person;

Old solution:

With help from @Schwern I managed to put up this query, which seems to work!

SELECT CONCAT(
'[',
GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),
']'
)
FROM person;

JSON encode MySQL results then read using jQuery

Here I try to give you some idea.

Make associative array in PHP using key => value pair like

$data = array('id' => 1, 'quat' => 10, 'id' => 2, 'quat' => 20)

and then send it as json_encode() like

header('Content-type: application/json');  // don't miss it
echo json_encode(array('data' => $data));

In jQuery

$.post('edit/producomponentes.php',{id:id},function(response){
//READ data HERE.
console.log(response.data); // you will get a json Object
}, 'json');
^-------- set dataType as json, then you don't any extra parse effort

According to edit

 $.post('edit/producomponentes.php',{id:id},function(data){
$.each(data, function(index, value) {
console.log(value.componente);
console.log(value.quantidade);
});
}, 'json');

Getting mysqli result as array for json_encode() in PHP

I ended up using PDO as it seems to much easier than mysqli:

$stmt = $db->prepare("select * from .....");
$stmt->execute(array($lastname));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
print json_encode($rows);


Related Topics



Leave a reply



Submit