Array only loads last PHP record with PDO

Asked

Viewed 53 times

1

I’m generating the information, but it only fills the last line of the query executed inside the Array, even though I’m sure it’s running all the lines in the foreach. Does anyone have any idea how to fill in all 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() ;
}

?>

1 answer

1


You are always overriding the array value. That’s why you only fill the last line. The right is to add the values that are redeemed in the bank, thus:

$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 the fetchAll already returns an array. Soon, you could turn it into json directly:

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

Browser other questions tagged

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