You need to enable JavaScript to run this app. 为什么我的PHP代码无法从数据库获取完整的多行查询结果
优惠活动
大模型
产品
解决方案
定价
更多

为什么我的PHP代码无法从数据库获取完整的多行查询结果

只输出单条记录的原因

表格行的输出代码放错位置了,被你写在了while循环外部。
while循环的作用是逐行读取数据库的查询结果,你当前只在循环内部给变量赋值,等循环跑完,所有变量只会留存最后一条记录的值,之后只执行一次表格行输出,自然只能看到单条数据。

修正方案

把输出表格行的代码移到while循环内部,每读一行数据库结果就输出一行对应的表格内容。修正后的完整代码如下:

<?php 
require 'db_conn.php';
$q1 = "select * from contact";
$res = mysqli_query($conn, $q1);
// 加个查询校验,避免数据库异常时报错干扰
if (!$res) {
    die("查询出错: " . mysqli_error($conn));
}
echo "
<table class='table'>
    <thead class='thead-dark'>
        <tr>
            <th scope='col'>#</th>
            <th scope='col'>id</th>
            <th scope='col'>Address</th>
            <th scope='col'>City</th>
            <th scope='col'>Country</th>
            <th scope='col'>State</th>
            <th scope='col'>Zip</th>
            <th scope='col'>Phone</th>
            <th scope='col'>#</th>
        </tr>
    </thead>
    <tbody>";

while ($row = mysqli_fetch_assoc($res)) 
{
    $id = $row["id"];
    $address = $row["address"];
    $city = $row["city"];
    $country = $row["country"];
    $state = $row["state"];
    $zip = $row["zip"];
    $phone = $row["phone"];
    // 每循环一次输出一行表格内容
    echo "
    <tr>
        <td> <input type='checkbox' name=''> </td>
        <td>$id</td>
        <td>$address</td>
        <td>$city</td>
        <td>$country</td>
        <td>$state</td>
        <td>$zip</td>
        <td>$phone</td>
    </tr>";
}

echo "
    </tbody>
</table>";
?>
可选优化
  • 增加查询结果的合法性校验,避免数据库连接失败、查询语句写错时,出现调用非对象的报错
  • 输出前对字段值做转义处理,防范XSS注入风险

内容的提问来源于stack exchange,提问作者Parakh Chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.29 17:27:04