-2

Well, this is my code:

<?php
 
header("Content-Type:application/json");
include('connection.php');
 
 
 $query = "SELECT * FROM users";
 $result = mysqli_query($con,$query);
 
 while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
     $customerData['id'] = $row['id'];
     $customerData['username'] = $row['username'];
     $customerData['password'] = $row['password'];
     $customerData['created'] = $row['created_at'];
 
     $response["users"] = $customerData;
 }
 

echo json_encode($response); exit;
 
?>

Currently I have two users in my database. What this code should do is to display all users in my database. At the moment the code works only so that only one user is shown. Does someone know what I have to change? Thanks in advise.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Does this answer your question? [mysqli\_fetch\_array while loop columns](https://stackoverflow.com/questions/14456529/mysqli-fetch-array-while-loop-columns) – Monnomcjo Mar 02 '21 at 09:33
  • 2
    You are over-writing `$response["users"]` on each iteration of the loop. You need to `append` new data to that array - like `$response["users"][]=$customerData;` - the answer below suggests that but does not say so – Professor Abronsius Mar 02 '21 at 09:33
  • 1
    If you changed your select to just return the columns you use, you might just be able to use `mysqli_fetch_all` and not have to use a loop at all. – Nigel Ren Mar 02 '21 at 09:38

1 Answers1

0

You need to append to the $response["users"] array. You're currently overwriting it with each loop/iteration.

You can use array_push() to accomplish this e.g., array_push($response['users'], $customerData); or do it without a function call by simply appending brackets to the end of your assignment like so: $response['users'][] = $customerData;

bedlam
  • 357
  • 3
  • 9