How to return all data from a SQL query out of function?

4

I have a function that aims to show all the results of an SQL query to the database and need to mount a view with the data of that query.

The function is as follows:

function buscar_banner(){

    global $pdo;
    $sql = "SELECT * FROM tb_banners WHERE status = '1'";
    $exc = $pdo->query($sql);
    $cnt = $exc->rowCount();

    return $exc->fetch();                       <--- Não sei se uso este
    return $exc->fetchAll();                    <--- ou este ...

}

$dados = buscar_banner();
  

TABLE

  • ID
  • title
  • sentence1
  • phrase2
  • image
  • datacad

Since I have this data, I do not know how to return and what structure to use. If you use foreach or while . What I want to return is:

<p>Nome banner 1</p>
<p>Nome banner 2</p>
<p>Nome banner 3</p>
...

I have been able to do the process since you have only one result, but I could not do it from the moment I have to return a loop with the results found.

    
asked by anonymous 16.11.2015 / 10:58

1 answer

3

Use $exc->fetchAll(PDO::FETCH_ASSOC); will return the entire associative array search, where indices will be the names of your table columns.

Then a simple% of% in% with%:

foreach($dados as $row){
  echo '<p>'.$row['titulo'].'</p><br />'//escape de linha por precaução
}

References:

PHP.net Documentation

    
16.11.2015 / 11:25