Home > database >  I want to make a statement for select data from MySQL database. But output just show the last row da
I want to make a statement for select data from MySQL database. But output just show the last row da

Time:12-29

This is my PHP code:

<?php

include 'connection.php';

    $result = $connection->prepare ("SELECT * FROM daftar_mobil");
    $result->execute();

    while($row = $result->fetch(PDO::FETCH_ASSOC)){

        $response['status']= true;
        $response['message']='Data Tersedia';
        $response['data'] = [
            
        'no_plat' => $row['no_plat'],
        'tipe_kendaraan' => $row['tipe_kendaraan'],
        'id_alat'=> $row['id_alat']
        ];
       
    }
    $json = json_encode($response, JSON_PRETTY_PRINT);
    echo $json;
    ?>

This is output: (output not show all data. Just show the last row data from table)

{ "status": true, "message": "Data Tersedia", "data": { "no_plat": "AB7786DE", "tipe_kendaraan": "XENIA", "id_alat": "12" } }

CodePudding user response:

Push each row of results onto an array, and encode that.

<?php

include 'connection.php';

$result = $connection->prepare ("SELECT * FROM daftar_mobil");
$result->execute();
$responses = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)){
    $response = [
        'status' => true,
        'message' => 'Data Tersedia',
        'data' => [
            'no_plat' => $row['no_plat'],
            'tipe_kendaraan' => $row['tipe_kendaraan'],
            'id_alat'=> $row['id_alat']
        ]
    ];
    $responses[] = $response;
}
$json = json_encode($responses, JSON_PRETTY_PRINT);
echo $json;
?>
  • Related