编写一个php页面ex6_1.php,能够按照学号、姓名、院系查询mysql数据库school中student表里的记录数,结果分页显示,每页显示15条记录
时间: 2024-10-24 17:09:56 浏览: 17
在PHP中,我们可以使用MySQLi或PDO来连接数据库并执行SQL查询。这里是一个简单的示例,展示了如何编写一个名为`ex6_1.php`的页面,它会查询`school`数据库的`student`表,并按照学号、姓名、院系进行分页查询:
```php
<?php
// 数据库配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "school";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 每页显示的记录数
$records_per_page = 15;
// 获取当前页码(默认为第一页)
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $records_per_page;
// 查询条件
$search_terms = [
'student_number' => isset($_GET['student_number']) ? $_GET['student_number'] : '',
'name' => isset($_GET['name']) ? $_GET['name'] : '',
'department' => isset($_GET['department']) ? $_GET['department'] : '',
];
$sql = "SELECT COUNT(*) AS total_records FROM student ";
$sql .= "WHERE " . implode(' AND ', array_keys($search_terms)) . " LIKE '%$search_terms%'";
$result_count = $conn->query($sql);
$total_records = $result_count->fetch_assoc()['total_records'];
$sql = "SELECT * FROM student ";
$sql .= "WHERE " . implode(' AND ', array_keys($search_terms)) . " LIKE '%$search_terms%' ";
$sql .= "LIMIT $start, $records_per_page";
$result = $conn->query($sql);
// 分页导航
echo "<ul class='pagination'>";
for ($i = 1; $i <= ceil($total_records / $records_per_page); $i++) {
echo "<li><a href='ex6_1.php?page=$i'>$i</a></li>";
}
echo "</ul>";
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "学号: " . $row["student_number"] . ", 姓名: " . $row["name"] . ", 院系: " . $row["department"] . "<br>";
}
} else {
echo "没有找到匹配的记录。";
}
// 关闭连接
$conn->close();
?>
阅读全文