在 html/php 表中显示来自 mysql 数据库的结果


Displaying results from mysql database in a html/php table

嗨,我有一个页面,我可以在其中查看 mysql 数据库的数据输出。 效果很好。 但它并不时尚。 所以我决定输入一个html <table>标签。 但是,它不显示数据。

我试过输入

<td> </td>行之间的等,但它会停止解析代码。

<?php
    $servername = "******";
    $username = "root";
    $password = "********";
    $dbname = "test2";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
         die("Connection failed: " . $conn->connect_error);
    }
    $sql = "SELECT first_name, last_name, email FROM person_list";
    $result = $conn->query($sql);

    //display table
    echo "<table border='1'>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
    </tr>";
           if ($result->num_rows > 0) {
         // output data of each row
         while($row = $result->fetch_assoc()) {
           echo
     "<br>   ". $row["first_name"]. " "
                                   . $row["last_name"] ." "
                                    . $row["email"] ." " ;
        }
    }
     else {
         echo "0 results";
    }
    echo "</table>";
    $conn->close();
    ?>

试试这个,如果它适合你的话。

echo "<table border='1'>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Email</th>
    </tr>";
       if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
       echo "<tr>";
       echo "<td>". $row["first_name"] . "</td>";
       echo "<td>". $row["last_name"] . "</td>";
       echo "<td>". $row["email"] . "</td> " ;
       echo "</tr>";
    }
}
echo "</table>";

你也可能对foreach的方式感兴趣。

Foreach在更大的数据集中会更快,但这与Narendrasingh Sisodia的答案非常相似。

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>";
if($result->num_rows > 0){
    foreach($result as $row){
        echo "<tr>";
        echo "<td>". $row["first_name"] . "</td>";
        echo "<td>". $row["last_name"] . "</td>";
        echo "<td>". $row["email"] . "</td> " ;
        echo "</tr>";
     }
}
echo "</table>";