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

Asked

Viewed 705 times

-1

I need to do a database search on a date variable 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 (makes available when loading the page):

$anos = Postagens::getDataAnos();

In the 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 have now in the bank 4 dates a 2011, two 2015 and one 2017. What should be returning me an array with [0] - 2011, [1] - 2015, [2] - 2017. But the var_dumps I put this showing this:

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

I’ve tried to change this line in the bank:

return $resultado->fetch_array(MYSQL_NUM); 

Ai the return of the var_dumps changes to:

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

I put only the parts of the code that I found relevant to the problem, it is my first question here, I hope to have been able to demonstrate the problem and I thank you for any help.

  • You are using PDO to connect to the database?

1 answer

0

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

public function executarSQL2($sql)
{

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

Receiving data in view

As the function getDataAnos returns a two-dimensional array the content for loop must be modified so that the variable $a is not printed (since it represents a vector). Finally, it can be solved like this:

 echo "  <input type='radio' name='filtro' value=" . $a['ano']. ">" . $a['ano']. "<br>";
  • You solved the problem, thank you very much! But a new problem has appeared In the same code from the previous view var dumps is returned right: array(3) { [0]=> array(1) { [0]=> string(4) "2011" } [1]=> array(1) { [0]=> string(4) "2015" } [2]=> array(1) { [0]=> string(4) "2017" } } But when displaying in html instead of showing the years this showing only ARRAY and the error: Array to string Conversion in C: xampp htdocs Trabblog views list.php on line 50

  • edited the answer.

Browser other questions tagged

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