要在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
替换为您的实际数据库连接信息和表名、列名。