我有一个名为成员的表,其中有3行。以下代码尝试显示成员表中的所有行。它显示3次第1条记录,而不是显示每条记录一次。

<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
    printf("Connection failed: %s\n", mysqli_connect_error());
    exit();
}
    $sql = "SELECT * FROM members";
    $res = mysqli_query($con,$sql);
    $num = mysqli_num_rows($res);
    $array = mysqli_fetch_assoc($res);
    $keysarray = array_keys($array);
    $valuearray = array_values($array);
    for ($i=0; $i < $num; $i++) {
        for($j = 0; $j < count($array); $j++) {
            echo "<table>";
            echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
            echo "</table>";
            }
            echo "<br><br>";
        }
    mysqli_close($con);
?>


我已经根据建议更新了此内容:

$sql = "SELECT * FROM members";
    $res = mysqli_query($con,$sql);
    $num = mysqli_num_rows($res);
    $array = mysqli_fetch_assoc($res);
    while ($row = mysqli_fetch_assoc($res)) {
        foreach($array as $key => $value){
            echo "<table>";
            echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
            echo "</table>";
            }
        echo "<br><br>";
        }

最佳答案

如果您有$array = mysqli_fetch_assoc($res);,您将仅从数据库中收到一行。您需要类似:

while ($row=mysqli_fetch_assoc($res))
{

// processing for each row

}

关于php - 我如何遍历表中的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13403398/

10-11 00:43