如何用 HTML 获取数据库数据
引入数据库
在 HTML 中,无法直接访问数据库。需要使用后端技术,例如 PHP、JavaScript 或 Python,从数据库中获取数据。
使用 PHP
PHP 是一个流行的后端语言,可以轻松连接到数据库。以下是一个示例代码:
<code class="php"><?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new <a style=\'color:#f60; text-decoration:underline;\' href="https://www.php.cn/zt/15713.html" target="_blank">mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 准备查询
$sql = "SELECT * FROM table_name";
// 执行查询
$result = $conn->query($sql);
// 检索数据
while ($row = $result->fetch_assoc()) {
echo $row["column_name"];
}
// 关闭连接
$conn->close();
?>




