PHP的while循环只返回第一个

时间:2020-09-16 12:21:23

标签: php arrays loops

我的循环在数组中仅产生1个结果:

<?php

$term = $_GET['term'];


$query = "SELECT * FROM Bob WHERE h_city LIKE '%".$term."%' ORDER BY h_city ASC";
$result = mysqli_query($conn, $query);

   while($row = mysqli_fetch_assoc($result)) {
        $result = $row['h_city'];
        array_push($result);
    }
    $json = json_encode(array($result));
    echo $json;
?>

结果有点像:[“ example1”]在数组内只有1个值,而我想将它们全部显示为[“ example1”,“ example2”]。有什么想法我可能做错了吗?

1 个答案:

答案 0 :(得分:2)

我认为简单的代码更改将在这里为您带来好处,只需将所有行信息放入称为项(或有意义的任何其他名称)的数组中即可。

while($row = mysqli_fetch_assoc($result)) {
    $items[] = $row['h_city']; // add to an array called items
}
$json = json_encode($items);
echo $json;

我认为您的查询也可能是错误的,因为您要限制此处的城市列表:

WHERE h_city LIKE '%".$term."%'

仅应返回单个城市的比赛。

警告,您应该在提出问题的评论中倾听那些对您的代码提出批评的人。您犯了很多根本性的错误,如果有错误报告并可以看到,您可能会解决自己。

Little Bobby your script is at risk for SQL Injection Attacks. 了解有关preparedMySQLi语句的信息。甚至escaping the string都不安全!