要在PHP中顯示數據庫信息,您可以使用以下步驟:
mysqli
或PDO
擴展連接到數據庫。例如:$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "SELECT * FROM 表名";
$result = $conn->query($sql);
while
循環)迭代查詢結果,并將每行數據顯示在HTML表格中。例如:echo "<table>";
echo "<tr><th>列名1</th><th>列名2</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["列名1"]."</td><td>".$row["列名2"]."</td></tr>";
}
echo "</table>";
完整的示例代碼如下:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
$sql = "SELECT * FROM 表名";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>";
echo "<tr><th>列名1</th><th>列名2</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["列名1"]."</td><td>".$row["列名2"]."</td></tr>";
}
echo "</table>";
} else {
echo "沒有結果";
}
$conn->close();
請注意,將代碼中的$servername
、$username
、$password
和$dbname
替換為您的實際數據庫連接信息和表名、列名。