在PHP中,可以使用HTML表格来输出数据库中的数据。
假设我们有一个数据库表格叫做“users”,包含了id、name和email字段。
首先,连接到数据库:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
然后,查询数据库中的数据并将结果存储在一个变量中:
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
接下来,使用HTML表格来输出查询结果:
if (mysqli_num_rows($result) > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["email"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
最后,关闭数据库连接:
mysqli_close($conn);
完整的代码如下:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["email"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
mysqli_close($conn);
这样就可以将数据库中的数据使用HTML表格输出了。