Array only loads last record in PHP with PDO

1

I'm generating the information, but only fills the last line of the query executed inside the Array, even though I'm sure it's running all the rows in the foreach. Any ideas how to populate all the arrays with all the information?

<?php
header('Cache-Control: no-cache, must-revalidate'); 
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');

require_once('conexao.php');
$conexao = conexao();
$id_igreja = 1;

try{
$igreja = "1";
$sql = "SELECT descricao, data, hora FROM reuniao WHERE id_igreja = :igreja order by 2,3 LIMIT 1";
$stmt = $conexao->prepare($sql);
$stmt->bindParam(':igreja', $id_igreja);
$stmt->execute();
$dados = $stmt->fetchAll(PDO::FETCH_OBJ);

  foreach ($dados as $consulta){
    $arr = [
    'descricao' => $consulta->descricao,
    'periodo' => $consulta->data,
    'hora' => $consulta->hora
    ];
}
$json = json_encode($arr,JSON_PRETTY_PRINT);
$fp = fopen("reuniao.json", "a");
fwrite($fp, $json);
fclose($fp);
echo $json;
}
catch(PDOException $e) {
echo 'ERRO: ' . $e->getMessage() ;
}

?>
    
asked by anonymous 11.08.2018 / 21:36

1 answer

1

You are always replacing the array value. That's why it only fills the last line. The right thing is to add the values that are redeemed in the bank, like this:

$arr = [];
foreach ($dados as $consulta){
    // adiciona mais um registro no array $arr
    $arr[] = [
    'descricao' => $consulta->descricao,
    'periodo' => $consulta->data,
    'hora' => $consulta->hora
    ];
}

Although it may be unnecessary, since fetchAll already returns an array. So you could turn it into json directly:

$dados = $stmt->fetchAll(PDO::FETCH_OBJ);
$json = json_encode($dados ,JSON_PRETTY_PRINT);
    
11.08.2018 / 22:21