Home > Net >  How to in PHP display more then one result from MySQLi
How to in PHP display more then one result from MySQLi

Time:11-26

I'm trying this code

        <?php
        $sql = 'SELECT * FROM users ORDER BY id DESC';
        $result = mysqli_query($mysql_db, $sql);
        ?>
        <table class="table">
            <thead class="thead-dark">
                <tr>
                    <th scope="col">ID</th>
                    <th scope="col">Username</th>
                    <th scope="col">MD5 Password</th>
                    <th scope="col">HWID</th>
                    <th scope="col">Time</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <?php while ($row = mysqli_fetch_array($result)) {
                        echo "<td>" . $row[0] . "</td>";
                        echo "<td>" . $row[1] . "</td>";
                        echo "<td>" . $row[2] . "</td>";
                        echo "<td>" . $row[3] . "</td>";
                        echo "<td>" . $row[4] . "</td>\n\n";
                    }
                    ?>
                 </tr>
            </tbody>
        </table>

But anyway it show results not correctly, i'm not finded anything about this in internet (I could not formulate the correct question)

CodePudding user response:

The <tr> should be inside the loop, so you create a new table row for each row of results.

            <tbody>
                <?php while ($row = mysqli_fetch_array($result)) {
                    echo "<tr>";
                    echo "<td>" . $row[0] . "</td>";
                    echo "<td>" . $row[1] . "</td>";
                    echo "<td>" . $row[2] . "</td>";
                    echo "<td>" . $row[3] . "</td>";
                    echo "<td>" . $row[4] . "</td>";
                    echo "</tr>\n";
                }
                ?>
            </tbody>

I also recommend you use $row['columname'] rather than numeric indexes, so you're not dependent on the order of the columns in the table definition. And then you can use mysqli_fetch_assoc() so it only returns the named fields.

  • Related