php - php while循环只显示数据库中的最后一行
问题描述
我正在尝试以 JSON 格式列出数据库中的所有行(当前为 2 行),但我得到的唯一输出是最后一行。
输出:
[{"id":"2","Name":"Googleplex","Address":"1600 Amphitheatre Pkwy, Mountain View, CA","Latitude":"37.421999","Longitude":"-122.083954"}]
代码:
if($status == "connected") {
$locations = $db->prepare('SELECT * FROM Locations');
$locations->execute();
$result = $locations->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $locations->fetch(PDO::FETCH_ASSOC))
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
}
解决方案
问题是你丢弃了你在这一行中读到的第一个结果:
$result = $locations->fetch(PDO::FETCH_ASSOC);
您可以将代码简化为
if ($status == "connected") {
$locations = $db->prepare('SELECT * FROM Locations');
$locations->execute() or die("Unable to execute query");
$resultArray = array();
while ($row = $locations->fetch(PDO::FETCH_ASSOC)) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
}
推荐阅读
- javascript - 如何从 contenteditable span 元素的开头删除输入(换行符)?
- php - 在其他子类(同一个父类)中使用父母子方法
- gnuplot - 将 x 值转换为分钟或小时
- python - 如何将字符串与列表项中的列表连接起来?
- solr - Solr 突出显示匹配的查询词
- svn - 通过 Web 界面进行 VisualSVNServer 问题验证
- java - 无法通过java应用程序连接到数据库mysql
- python - Python pandas UIPath - 列表分配索引超出范围
- php - 发送视频到服务器
- weebly - 在 Weebly 中编辑页面的 HTML