Mysql table return with PHP foreach

Asked

Viewed 44 times

-1

I have the event table and would like to return all rows of a Mysql query through the foreach in PHP, but it returns only the first line, can help me?

Follows the code:

<?php
include_once('evento/action/conexao.php');
    $database = new Database();
    $db = $database->conectar();

$data_selecionada = '2021-02-19';

$sql = "SELECT TIME(eventos.inicio) as ini, TIME(eventos.termino) as fim FROM eventos WHERE DATE(eventos.inicio) = '$data_selecionada' ORDER BY inicio";
$horarios = array();
$res = $db->prepare($sql);
$res->execute(); 
$dados = $res->fetch(PDO::FETCH_ASSOC);

foreach($dados as $dado) {
    echo "</br>" . $dado;
}

2 answers

1


The function you are using $res->fetch(PDO::FETCH_ASSOC); only returns the next line of the query, so that you return all the rows in the desired way you should create a while calling the function $res->fetch(PDO::FETCH_ASSOC); back to each interaction OR else use the function $res->fetchAll(); and then use the foreach in the variable $dados receiving the correct function.

  • 1

    thank you very much, it worked!

1

Hello, the function fetch() PDO returns an element and puts the pointer on the next, if you want all, use the fecthAll():

<?php
    include_once('evento/action/conexao.php');
    $database = new Database();
    $db = $database->conectar();

    $data_selecionada = '2021-02-19';

    $sql = "SELECT TIME(eventos.inicio) as ini, TIME(eventos.termino) as fim FROM 
       eventos WHERE DATE(eventos.inicio) = '$data_selecionada' ORDER BY inicio";
    $horarios = array();
    $res = $db->prepare($sql);
    $res->execute(); 
    //o erro está aqui... utilize fetchAll()
    //$dados = $res->fetch(PDO::FETCH_ASSOC);
    $dados = $res->fetchAll(PDO::FETCH_ASSOC);
    foreach($dados as $dado) {
        echo "</br>" . $dado;
    }
  • thank you very much, it worked!

  • Arrange, we are here for that. If you can, accept the reply to mark as solved. See more.

Browser other questions tagged

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