게시글 리스트 페이지에 다음과 같이 코드를 수정했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="member2.css">
<title>회원게시판</title>
</head>
<body>
<h2>회원 게시판</h2>
<div class="list">
<form class="search-form" method="GET" action="">
<input name="search_keyword" type="text" placeholder="검색어를 입력하세요">
<button type="submit">검색</button>
</form>
<table>
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
<th>등록일</th>
</tr>
</thead>
<tbody>
<?php
$conn = mysqli_connect("localhost", "", "", "");
$sql = "SELECT * FROM memberboard order by board_num desc";
// 게시글 검색
$search_keyword = $_GET['search_keyword'] ?? '';
if (!empty($search_keyword)) {
$sql = "SELECT * FROM memberboard WHERE title LIKE '%$search_keyword%' OR username LIKE '%$search_keyword%' order by board_num desc";
}
$result = mysqli_query($conn, $sql);
$total_record = mysqli_num_rows($result);
// 페이징 추가코드
$posts_per_page = 10; // 한 페이지당 게시글 수
$total_pages = ceil($total_record / $posts_per_page); // 전체 페이지 수
$current_page = isset($_GET['page']) ? $_GET['page'] : 1; // 현재 페이지 번호
$start = ($current_page - 1) * $posts_per_page; // 시작 레코드 인덱스
$sql .= " LIMIT $start, $posts_per_page"; // 쿼리에 LIMIT 구문 추가
$result = mysqli_query($conn, $sql);
for ($i = 0; $i < mysqli_num_rows($result); $i++) {
mysqli_data_seek($result, $i);
$row = mysqli_fetch_assoc($result);
$num = $row["board_num"];
$title = $row["title"];
$name = $row["username"];
$date = $row["wr_date"];
echo "<tr>";
echo "<td>{$num}</td>";
echo "<td><a href='member_view.php?num={$num}'>{$title}</a></td>";
echo "<td>{$name}</td>";
echo "<td>{$date}</td>";
echo "</tr>";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<!-- 페이지 넘버 -->
<div class="pagination">
<?php
for ($page = 1; $page <= $total_pages; $page++) {
echo "<a href='member_list.php?page={$page}'>{$page}</a> ";
}
?>
</div>
<div class="buttons">
<button onclick="location.href='member_list.php'">목록</button>
<button onclick="location.href='member_form.php'">글쓰기</button>
</div>
</body>
</html>
|
cs |
페이징을 위해 추가된 코드는 39~45, 73~79번 줄이다.
39 : 한 페이지당 10개의 게시글을 출력했다
40 : 전체 게시글 수를 10으로 나눈 수를 올림하여 총 페이지 수를 $total_pages변수에 저장
42 : $current_page 변수는 $_GET['page']로부터 현재 페이지 번호를 가져오고, GET 매개변수가 없을 경우 1로 설정했다
43 : 가져올 게시글의 시작 인덱스를 계산하기 위한 변수.
45 : 쿼리에 limit 절 추가
73 ~ 79 : 페이지 넘버 출력
'Hacking_study > 개발과제' 카테고리의 다른 글
8주차_(2) 파일 다운로드 (0) | 2023.06.04 |
---|---|
8주차_(1) 파일 업로드 (0) | 2023.06.03 |
6주차_(3) 회원 게시판 글 검색 (0) | 2023.05.31 |
6주차_(2) 회원 게시판 글 수정 (0) | 2023.05.28 |
6주차_(1) 회원 게시판 글 삭제 (0) | 2023.05.16 |