1

I am trying to retrieve the data from mySQL and generate as JSON file.
But the output is just showing only 1 row.
There are many rows inside the database table.
What is wrong with this code?

$sql = "SELECT * FROM form_element";
$result = mysqli_query($conn, $sql);
$response = array();
$data_array = array();
if (mysqli_num_rows($result) > 0) {
   // output data of each row
   while($data = mysqli_fetch_assoc($result)) {
      $id = $data['id'];
      $name = $data['name'];
      $email = $data['email'];
      $phone = $data['phone'];
      $address = $data['address'];
      $data_array = array(
         'name' => $name, 
         'email' => $email, 
         'phone' => $phone, 
         'address' =>  $address
      );
   }
} else {
   echo "0 results";
}
$response['data_array'] = $data_array;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));

1 Answer 1

3

You're overwriting $data_array every time in the loop.

So, this part:

$data_array = array(
  'name' => $name, 
  'email' => $email, 
  'phone' => $phone, 
  'address' =>  $address
);

should be changed to:

$data_array[] = array(
  'name' => $name, 
  'email' => $email, 
  'phone' => $phone, 
  'address' =>  $address
);

Then each row is added to the $data_array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.