Generate array in JSON by PHP

0

I'm studying a way to send a JSON response from PHP to JS. I've looked at various posts here and in other forums, but I can not find my error.

I do a SELECT all of it in a MySQL table through PHP, but when I send it to JS and see the response on the console, only one result is shown, the first, not the others.

There is probably something wrong with my PHP, as JS only shows the result on the console.

In the code there is a snippet like this:

($result->num_rows > 5)

This section is purposeful, because I wanted to test if I would receive a result equally, I know the correct thing 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);
   }
    
asked by anonymous 28.02.2018 / 04:45

1 answer

1

You are only getting one 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, you need to create a multidimensional array in> . Example:

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

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

    
28.02.2018 / 05:22