在Web开发中,表格是一个常用的元素之一。无论是用于展示数据、收集信息,还是进行计算,表格都是不可或缺的工具。而PHP作为一种流行的服务器端编程语言,可以通过查询数据库的方式获取数据,并将其填入表格中展示给用户。本文将介绍如何使用PHP查询结果填入表格的方法。
//连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); //检测连接是否成功 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
//查询数据 $sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); //检测查询是否成功 if (mysqli_num_rows($result) > 0) { //输出每一行数据 while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>"; } } else { echo "0 results"; }
<table> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </table>
然后,我们需要在PHP代码中遍历查询结果,将每一行数据填入表格中。下面是将查询结果填入表格的示例代码:
//创建表格,并填入数据 echo "<table>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>Name</th>"; echo "<th>Age</th>"; echo "</tr>"; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["age"] . "</td>"; echo "</tr>"; } } else { echo "0 results"; } echo "</table>";
//连接数据库 $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); //检测连接是否成功 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } //查询数据 $sql = "SELECT * FROM students"; $result = mysqli_query($conn, $sql); //创建表格,并填入数据 echo "<table>"; echo "<tr>"; echo "<th>ID</th>"; echo "<th>Name</th>"; echo "<th>Age</th>"; echo "</tr>"; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row["id"] . "</td>"; echo "<td>" . $row["name"] . "</td>"; echo "<td>" . $row["age"] . "</td>"; echo "</tr>"; } } else { echo "0 results"; } echo "</table>"; //关闭连接 mysqli_close($conn);
以上示例代码仅仅是一个演示,开发者可以根据自己的需求进行修改。比如,可以通过SQL语句筛选出符合特定条件的数据,或者通过CSS样式美化表格的外观等等。希望本文能为使用PHP查询结果填入表格的开发者提供一些帮助。
以上是php怎么将查询结果填入表格的详细内容。更多信息请关注PHP中文网其他相关文章!