要使用PHP和HTML显示MySQL数据,你需要执行以下步骤:
以下是一个简单的示例,展示如何使用PHP连接MySQL数据库并显示数据:
首先,确保你有一个MySQL数据库和一个表。例如,创建一个名为users
的表:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
创建一个PHP文件(例如index.php
),用于连接到数据库并获取数据:
<?php
// 数据库配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询数据
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// 检查是否有结果
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"]. "</td>";
echo "<td>" . $row["name"]. "</td>";
echo "<td>" . $row["email"]. "</td>";
echo "</tr>";
}
} else {
echo "0 结果";
}
// 关闭连接
$conn->close();
?>
在同一个文件中,添加HTML结构来显示数据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>显示MySQL数据</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 15px;
text-align: left;
}
</style>
</head>
<body>
<h2>用户列表</h2>
<table>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
</tr>
<!-- PHP代码插入到这里 -->
<?php include 'index.php'; ?>
</table>
</body>
</html>
<?php
// 数据库配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 预处理语句
$stmt = $conn->prepare("SELECT id, name, email FROM users");
$stmt->execute();
$result = $stmt->get_result();
// 输出数据
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"]. "</td>";
echo "<td>" . $row["name"]. "</td>";
echo "<td>" . $row["email"]. "</td>";
echo "</tr>";
}
// 关闭连接
$stmt->close();
$conn->close();
?>
通过这种方式,你可以更安全地从MySQL数据库中获取并显示数据。
领取专属 10元无门槛券
手把手带您无忧上云