Return array in SQL in a php variable, for later assembly of HTML

0

I need to do a database search on a variable date and return only the Years. For this I did the following:

In Control:

public static function getDataAnos() {
    $bd = new Banco(BANCO_HOST, BANCO_USUARIO, BANCO_SENHA, BANCO_BASE_DADOS);

    $sql = "SELECT YEAR (postagens.data) as ano FROM postagens GROUP BY ano";
    return $bd->executarSQL2($sql);
}

In the library to access the Bank:

public function executarSQL2($sql)
{

    $resultado = $this->query($sql);     
    return $resultado->fetch_array();    
}

In control (available when loading page):

$anos = Postagens::getDataAnos();

In Vision:

<?php
  if ($anos !== false) {
      echo "<div id='filtros'>";
      var_dump($anos);
      foreach ($anos as $a) {
          echo "  <input type='radio' name='filtro' value=" . $a. ">" . $a. "<br>";
      }
      echo "</div>";
  }
?>

THE PROBLEM:

I currently have in the database 4 dates one 2011, two 2015 and one 2017. What should be returning me an array with [0] - 2011, [1] - 2015, [2] - 2017. But the var_dumps that I put this showing this:

array(2) { [0]=> string(4) "2011" ["ano"]=> string(4) "2011" }

I've tried changing this line on the bank:

return $resultado->fetch_array(MYSQL_NUM); 

Then the return of var_dumps changes to:

array(1) { [0]=> string(4) "2011" } 

I just put the parts of the code that I found relevant to the problem, it's my first question here, I hope I've been able to demonstrate the problem and thank you in advance for any help.

    
asked by anonymous 14.11.2017 / 21:41

1 answer

0

The problem is that the function fetch_array returns only the next row of resultset returned in the query() function. To return all the lines of the resultset you can use the function fetch_all() .

public function executarSQL2($sql)
{

    $resultado = $this->query($sql);     
    return $resultado->fetch_all();    
}

Receiving data in the view

Since the getDataAnos function returns an array of two dimensions the for loop contents must be modified so that the $a variable is not printed (since it represents a vector). In the end, you can solve it like this:

 echo "  <input type='radio' name='filtro' value=" . $a['ano']. ">" . $a['ano']. "<br>";
    
14.11.2017 / 23:55