0

I have write these kind of codes multiple times and it always worked great but now that I am on a different system it shows only 1 result.

the query is simple

$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DATABASE = 'db_test';


$con = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DATABASE);

$sql = "SELECT * FROM test ";

$res = mysqli_query($con,$sql);

$res_array = mysqli_fetch_assoc($res);

echo json_encode($res_array);

mysqli_free_result($res);

mysqli_close($con);

I wonder if there is any settings that I have to change before running the app

Mohamad Pishdad
  • 329
  • 3
  • 11

3 Answers3

1

Seriously, it's all over the docs:

mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Note "the fetched row" part.

You need to do put your gathering in a cycle

$rows = [];

/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row
}

json_encode($rows);
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
0

This line $res_array = mysqli_fetch_assoc($res); will only fetch one record.

You need to loop over result-set object and get all data from that.So use while() loop like below

$res_array =[];
while($row = mysqli_fetch_assoc($res)){
  $res_array[] = $row;
}

Reference:-

mysqli_fetch_assoc()

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
-1

Replace this line

$res_array = mysqli_fetch_assoc($res);

with

while ($row = mysqli_fetch_assoc($res)) {
    $res_array[] = $row;
}
ild flue
  • 1,323
  • 8
  • 9