How to return all data from an SQL query outside of Function?

Asked

Viewed 352 times

4

I have a function which has the objective of showing all the results of an SQL query to the database and need to assemble a view with the data of this query.

To function is the following:

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
  • phrase1
  • phrase2
  • image
  • datacad

Once I have this data, I don’t know how to return and what structure to use. If I use a 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 was able to do the process as long as there was only one result, but I could not do from the moment I have to return one loop with the results found.

  • How’s your tb_banners table?

  • My project is procedural. I have no technical levels to develop such in POO yet. I appreciate your reply to help me.

1 answer

3


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

Then a simple foreach in $dados:

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

References:

PHP.net Documentation

Browser other questions tagged

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