我想为来自 MySQL 数据库的 select 数据做一个声明。但输出只显示来自 table 的最后一行数据
I want to make a statement for select data from MySQL database. But output just show the last row data from table
这是我的 PHP 代码:
<?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;
?>
这是输出:(输出不显示所有数据。只显示来自 table 的最后一行数据)
{ "status": true, "message": "Data Tersedia", "data": { "no_plat":
"AB7786DE", "tipe_kendaraan": "XENIA", "id_alat": "12" } }
将每一行结果推送到一个数组中,然后对其进行编码。
<?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;
?>
这是我的 PHP 代码:
<?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;
?>
这是输出:(输出不显示所有数据。只显示来自 table 的最后一行数据)
{ "status": true, "message": "Data Tersedia", "data": { "no_plat": "AB7786DE", "tipe_kendaraan": "XENIA", "id_alat": "12" } }
将每一行结果推送到一个数组中,然后对其进行编码。
<?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;
?>