在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表格輸出了。