I have a query (mysql) in php which when encoded to json only return the last result of the query however I am sure that the query returns more than one result:
$counter=0;
$reply=array();
$result = mysqli_query($conn,$stringQuery);;
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$reply["json"]=$row;
$counter++;
}
echo json_encode($reply);
} else {
echo json_encode("0 results");
}
$conn->close();
when I stringify the result in javascript it only return the last entry of the table, or single result:
$.ajax({
type: 'POST',
url: 'SearchQuery.php',
data: {
'json': cond
},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
dataType: 'json',
success: function(response) {
alert(JSON.stringify(response["json"]));
}
});
Try this:
while ($row = mysqli_fetch_assoc($result)) {
$reply[] = $row;
// ^^^^^^^^^^^^^
$counter++;
}
echo json_encode($reply);
Try to change fetch_assoc() with fetch_array()
while($row=$result->fetch_array()){
$reply[] = $row;
$counter++;
}
echo json_encode($reply);
Or try:
while($row=$result->fetch_array()){
$items.=<<<EOD
{
"r": "{$row['yourfield']}",
},
EOD;
$counter++;
}
header('Content-type: application/json');
?>
{
"response": [
<?php echo $item;?>
]
}
Here
$reply["json"]=$row;
in this line your last fetch row in while loop overwrite existing result so it is showing only last row as a result.
You can try
$reply["json"][]=$row;
So at ajax in success function
alert(JSON.stringify(response["json"]));
you can have a data accessible via key name "json".