PHP 读取学生数据库并显示到网页 - 详细步骤及代码示例
-
连接数据库: 使用 PHP 的
mysqli或PDO扩展连接到 MySQL 数据库。 -
查询数据: 使用
SELECT语句查询student表内的数据。 -
获取查询结果: 使用
mysqli或PDO扩展的fetch方法获取查询结果集。 -
显示数据: 使用 HTML 和 PHP 的
echo语句将查询结果显示在网页中。可以使用表格或列表等 HTML 元素将数据显示得更加美观。
以下是示例代码:
// 连接数据库
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'database';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// 查询数据
$sql = 'SELECT xuehao, name, age, score, address FROM student';
$result = $conn->query($sql);
// 显示数据
if ($result->num_rows > 0) {
echo '<table><tr><th>学号</th><th>姓名</th><th>年龄</th><th>分数</th><th>地址</th></tr>';
while ($row = $result->fetch_assoc()) {
echo '<tr><td>' . $row['xuehao'] . '</td><td>' . $row['name'] . '</td><td>' . $row['age'] . '</td><td>' . $row['score'] . '</td><td>' . $row['address'] . '</td></tr>';
}
echo '</table>';
} else {
echo '0 results';
}
// 关闭连接
$conn->close();
原文地址: https://www.cveoy.top/t/topic/fZYI 著作权归作者所有。请勿转载和采集!