简体   繁体   English

如何遍历表中的行

[英]how do I traverse rows in a table

I have a table named members with 3 rows. 我有一个名为3行的成员表。 The following code attempts to display all the rows in the members table. 以下代码尝试显示成员表中的所有行。 It displays the 1'st record 3 times instead of displaying each record once. 它显示3次第一条记录,而不是显示每条记录一次。

<?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);
?>

I've updated this per suggestions: 我已经根据建议更新了此内容:

$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>";
        }

这是因为,您的$ num = 3,count($ array)= 3,而外部for循环与内部for循环无关。

Any basic tutorial will tell you this. 任何基础教程都会告诉您这一点。 Even the PHP docs provide an example. 甚至PHP文档也提供了一个示例。

Where you have $array = mysqli_fetch_assoc($res); 你在哪里$array = mysqli_fetch_assoc($res); , you will only receive one row from your database. ,您只会从数据库中收到一行。 You need something like: 您需要类似:

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

// processing for each row

}

you can use do something like this.. 您可以使用类似这样的方法。

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

    // processing for each row
    e.g
    echo $row['id'];
    echo $row['name'];
    etc
  }

try this... this peace of code is not tested but just to give you an idea... 试试这个...这种代码的安全性未经测试,只是给您一个想法...

$sql = "SELECT * FROM members";
    $res = mysqli_query($con,$sql);
    $num = mysqli_num_rows($res);
    while ($row = mysqli_fetch_assoc($res)) {
            echo "<table>";
            echo '<tr><td> id = "'.$row['id'].'": 
                  </td><td> name = "'.$row['name'].'"</td></tr>";
            echo "</table>";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM