gpt4 book ai didi

php - 通过PHP的sql查询总是跳过第一行

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:44 24 4
gpt4 key购买 nike

我遇到了一个奇怪的问题,我不知道这个问题是从哪里来的。我有一个名为 weather-app 的 mySQL 数据库,该表上有一个表 cities 我有一个美国所有城镇的列表(列 city人口)。

让我直接在我的 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

它对每个查询都这样做,而且只对第一行这样做。

我的代码:

index.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>

app.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;
}
});
}

fetch-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/>";
}
?>

result of http://localhost:8080/weather-app/config/fetch-cities.php?query=Boston:

最佳答案

这一行:

$row_count =$results->fetchColumn();

不返回行数。它从结果集的第一行返回第一列,并将指针移动到下一行,这就是为什么您稍后没有在 foreach 中获取第一行的原因。

关于php - 通过PHP的sql查询总是跳过第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59637393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com