Daniel Yantis Daniel Yantis - 3 months ago 9
JSON Question

how to return multiple record sets using json

I want to return multiple records instead of just 1 row.
JSON now returns only 1 row and I guess I need to add a while loop but not sure the right way to code it.

.js

function getq() {
var q = $("#q").val();

$.post(
'getq.php',
{q: q},
function(data) {
console.log(data);
}, "json"
);
}


getq.php

$q = $_POST['q'];
include("connect.php");
$sql = ("SELECT xxx FROM yyy WHERE zzz = $q");
if ($results=mysqli_query($db,$sql)) {
$result = $results->fetch_assoc();
echo json_encode($result);
}

Answer

EDIT: I created the same case as yours on my pc, I used this javascript:

$.post('getq.php', {q: q}, function(data) {
        console.log(data);
    }
);

And this php (getq.php) file:

<?php
// Create connection
$mysqli = new mysqli( "localhost", "user", "passw", "db");

$q = $_POST['q'];

if ($results = $mysqli->query("SELECT xxx FROM yyy WHERE zzz = $q", MYSQLI_USE_RESULT)) {
    $result_set = mysqli_fetch_all($results,MYSQLI_ASSOC);
    echo json_encode($result_set);
    $results->close();
 }
?>

source: W3Schools

Comments