php,从mysql表中查询数据,并使用for显示结果


php,query data from mysql table and display results using for each

基本上,我首先从mysql表中查询特定的列,并希望使用php中的foreach()将它们全部回显。这是我的密码。

$sql = "SELECT id, name, roll_no, email, title, abstract, supervisor, sub_date
        FROM student_data";
$result = $conn->query($sql);
$array = $result->fetch_assoc();
foreach ($array as $x => $value)
{
    echo $array["id"] . " " . $array["name"] . " " . $array["roll_no"] . " " . $array["title"] . " " . $array["supervisor"] . " " . $array["sub_date"] ."<br><br>";
}

它只是不断重复第一个条目。

您只循环第一个结果集中的元素。您需要遍历整个结果集:

while($array= $result->fetch_assoc()) {
    echo $array["id"] . " " . $array["name"] . " " . $array["roll_no"] . " " . $array["title"] . " " . $array["supervisor"] . " " . $array["sub_date"] ."<br><br>";
}

您的主要误解是$array = $result->fetch_assoc();只返回一个结果。要获得第二个,您应该再次致电$result->fetch_assoc()。所以你应该以这种方式迭代

while ($array = $result->fetch_assoc()) {
echo $array["id"] . " " . $array["name"] . " " . $array["roll_no"] . " " . $array["title"] . " " . $array["supervisor"] . " " . $array["sub_date"] ."<br><br>";
}