Generate JSON array by PHP

Asked

Viewed 273 times

0

I’m studying a way to send a PHP JSON response to JS. I’ve looked at several posts here and in other forums, but I can’t find my mistake.

I make a SELECT of everything in a Mysql table through PHP, but when I send to JS and see the response in the console, only one result is shown, the first, not the others.

There’s probably something wrong with my PHP, because JS only shows the result on the console.

In the code there’s an excerpt like this:

($result->num_rows > 5)

This section is purposeful, because I wanted to test if I would receive a result equally, I know that the correct is to test if it is > 0.

PHP code:

    public function selectTable(){
     $return_arr = array();

     $sql = "SELECT * FROM coletas";
     $result = mysqli_query($this->mysqli, $sql);
     if ($result->num_rows > 5) {
       while($r = mysqli_fetch_assoc($result)) {
          $codigo_intervencao = $r['codigo_intervencao'];
          $sql2 = "SELECT intervencao FROM intervencoes WHERE id = $codigo_intervencao";
          $intervencao = mysqli_query($this->mysqli, $sql2);
          $intervencao2 = mysqli_fetch_assoc($intervencao);
          $return_arr['codigo_intervencao'] = $intervencao2['intervencao'];
          $return_arr['tempo'] = $r['tempo'];
       }
     }
     return json_encode($return_arr, JSON_FORCE_OBJECT);
   }

1 answer

1


You are only getting a result because you are overwriting the others, with the code below:

$return_arr['codigo_intervencao'] = $intervencao2['intervencao'];
$return_arr['tempo'] = $r['tempo'];

To return all, it is necessary to create a multidimensional array. Example:

$return_arr[]['codigo_intervencao'] = $intervencao2['intervencao'];
$return_arr[]['tempo'] = $r['tempo'];

This way you will be able to store all the values to display them later.

  • Great, it Works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.