php - 通过 PHP 的 sql 查询总是跳过第一行
问题描述
我面临一个奇怪的问题,我不知道这个问题来自哪里。我有一个 mySQL 数据库,该数据库weather-app
使用该表cities
上的一个表调用我有一个所有美国城镇的列表(列city
和population
)。
让我直接在我的 SQL 数据库上运行一个查询:
SELECT * FROM cities WHERE city LIKE 'boston' ORDER BY population DESC
结果我得到
1840000455 Boston MA 4637537
1840013902 Boston GA 1315
1840024721 Boston VA 674
1840026471 Boston PA 236
1840009492 Boston IN 130
1840026800 Boston KY 89
直接通过我的 PHP 进行的相同查询给了我:
1840013902 Boston GA 1315
1840024721 Boston VA 674
1840026471 Boston PA 236
1840009492 Boston IN 130
1840026800 Boston KY 89
它对每个查询都执行此操作,并且仅针对第一行。
我的代码:
索引.html
<body>
<?php require_once("config/db.php")?>
<h2>Weather</h2>
<input type="text" name="city-search" class="city-search" id="city-search">
<ul class="result">
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="scripts/app.js"></script>
</body>
应用程序.js
search.addEventListener("keyup", e =>{
let city = search.value;
if(city != ""){
loadCities(city);
}
});
const loadCities = (city) => {
$.ajax({
url: "config/fetch-cities.php",
method: "GET",
data: {
query: city
},
success: function(data){
results.innerHTML = data;
}
});
}
获取-cities.php
<?php
require("db.php");
if(isset($_GET["query"])){
$search = $_GET["query"];
$results = $conn->prepare("SELECT * FROM cities WHERE city LIKE '{$search}%'
ORDER BY population DESC");
}
$results->execute();
$row_count =$results->fetchColumn();
foreach ($results as $row) {
echo $row["city"] . "-" . $row["population"] ."<br/>";
}
?>
结果http://localhost:8080/weather-app/config/fetch-cities.php?query=Boston
:
解决方案
这一行:
$row_count =$results->fetchColumn();
不返回行数。它从结果集的第一行返回第一列并将指针移动到下一行,这就是为什么您foreach
以后没有得到第一行的原因。
推荐阅读
- docker - 尝试访问我的主机文件中设置的本地 IP 地址时出现 ERR_CONNECTION_REFUSED
- javascript - 模态javascript代码只能暂时工作?
- webpack - 为什么 webpack 在 Next.js 应用程序中保持下载?
- list - 在 PowerApps 中构建电子邮件家庭电子邮件功能
- python - Bluez-obex 和 python opp 服务器,如何更改文件的存储位置?
- javascript - styled-components:如何为 createGlobalStyle 创建和验证单例?
- amazon-dynamodb - 使用 `$utils.defaultIfNullOrEmpty` 保存布尔值
- c++ - 在父类方法中初始化派生类的静态变量
- sql - 将 Max() 与 GROUP BY 的其他字段一起使用
- html - 如何在添加到购物车按钮旁边移动数量输入字段 - wordpress