1. Ajax(Asynchronous JavaScript and XML)
: Ajax는 웹 페이지 전체를 다시 로딩하지 않고 웹 페이지의 일부분만을 갱신할 수 있게 한다.
Ajax는 백그라운드 영역에서 서버와 통신하여 그 결과를 웹 페이지 일부분에 표시한다.
2. Ajax의 장점
① 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신 할 수 있다.
② 웹 페이지가 로드된 후에 서버로 데이터 요청을 보낼 수 있다.
③ 웹 페이지가 로드된 후에 서버로부터 데이터를 받을 수 있다.
④ 백그라운드 영역에서 서버로 데이터를 보낼 수 있습니다.
3. Ajax의 단점
① Ajax는 클라이언트가 서버에 데이터를 요청하는 클라이언트 풀링 방식을 사용하므로
서버 푸시 방식의 실시간 서비스를 만들 수 없다.
② Ajax로는 바이너리 데이터를 보내거나 받을 수 없다.
③ Ajax 스크립트가 포함된 서버가 아닌 다른 서버로 Ajax 요청을 보낼 수 없다.
4. XMLHttpRequest 객체
: Ajax의 가장 핵심적인 구성 요소는 XMLHttpRequest(XHR) 객체이다.
Ajax에서 XMLHttpRequest 객체는 웹 브라우저가 서버와 데이터를 교환할 때 사용한다.
웹 브라우저가 백그라운드에서 계속해서 서버와 통신할 수 있는 것은 바로 이 객체를 사용하기 때문이다.
const XHR객체명 = new XMLHttpRequest();
5. onreadystatechange
① UNSENT(숫자 0) : XMLHttpRequest 객체가 생성됨
② OPENED(숫자 1) : open() 메소드가 성공적으로 실행됨
③ HEADERS_RECEIVED (숫자 2) : 모든 요청에 대한 응답이 도착함
④ LOADING (숫자 3) : 요청한 데이터를 처리중
⑤ DONE (숫자 4) : 요청한 데이터의 처리가 완료되어 응답할 준비가 완료됨
6. open(전달방식, URL 주소, 동기여부) 메소드
: open 메소드는 서버로 보낼 Ajax 요청의 형식을 설정한다.
** 전달 방식 : get, post 방식 중 하나를 선택한다.
** URL 주소 : 요청을 서리할 서버의 파일 주소를 전달한다.
** 동기여부 : 동기식, 비동기식으로 전달할지 결정한다. (true -> 비동기, false -> 동기)
7. send() 메소드
: send() 메소드는 작성된 Ajax 요청을 서버로 전달한다.
send(); // get방식
send(문자열); // post 방식
** 1_Ajax1.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax - 1</title>
<script>
function sendRequest() {
const httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState == XMLHttpRequest.DONE && httpRequest.status == 200) {
// Ajax 통신이 제대로 이루어졌을 경우
document.getElementById("text").innerHTML = httpRequest.responseText;
}
};
httpRequest.open("GET", "1_Ajax1_ok.php?userid=apple&userpw=1111", true);
httpRequest.send();
}
</script>
</head>
<body>
<h2>Ajax - 1</h2>
<p> get 방식으로 요청 : <input type="button" onclick="sendRequest()" value="get방식으로 요청 보내기"></p>
<p id="text"></p>
</body>
</html>
** 1_Ajax1_ok.php
<?php
$userid = $_GET['userid'];
$userpw = $_GET['userpw'];
echo($userid."<br>");
echo($userpw."<br>");
?>
8. 닉네임 중복 체크
** regist.php
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>회원가입</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="./js/regist.js"></script>
<script src="https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
function sample6_execDaumPostcode() {
new daum.Postcode({
oncomplete: function(data) {
// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
// 각 주소의 노출 규칙에 따라 주소를 조합한다.
// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
var addr = ''; // 주소 변수
var extraAddr = ''; // 참고항목 변수
//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
addr = data.roadAddress;
} else { // 사용자가 지번 주소를 선택했을 경우(J)
addr = data.jibunAddress;
}
// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
if(data.userSelectedType === 'R'){
// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraAddr += data.bname;
}
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraAddr !== ''){
extraAddr = ' (' + extraAddr + ')';
}
// 조합된 참고항목을 해당 필드에 넣는다.
document.getElementById("sample6_extraAddress").value = extraAddr;
} else {
document.getElementById("sample6_extraAddress").value = '';
}
// 우편번호와 주소 정보를 해당 필드에 넣는다.
document.getElementById('sample6_postcode').value = data.zonecode;
document.getElementById("sample6_address").value = addr;
// 커서를 상세주소 필드로 이동한다.
document.getElementById("sample6_detailAddress").focus();
}
}).open();
}
</script>
</head>
<body>
<h2>회원가입</h2>
<form name="regform" id="regform" method="post" action="regist_ok.php" onsubmit="return sendit()">
<input type="hidden" name="isIdCheck" id="isIdCheck" value="false">
<input type="hidden" name="isSsn" id="isSsn" value="false">
<p><label>아이디 : <input type="text" name="userid" id="userid" maxlength="20" onchange="isIdChange()"></label>
<input type="button" value="중복확인" onclick="idRegCheck()"></p>
<p id="idRegCheck_text"></p>
<p><label>비밀번호 : <input type="password" name="userpw" id="userpw" maxlength="20"></label></p>
<p><label>비밀번호 확인 : <input type="password" name="userpw_re" id="userpw_re" maxlength="20"></label></p>
<p><label>이름 : <input type="text" name="username" id="username"></label></p>
<p><label>휴대폰 번호 : <input type="text" name="hp" id="hp"></label> ('-' 을 포함)</p>
<p><label>이메일 : <input type="text" name="email" id="email"></label></p>
<p>취미 :
<label>드라이브<input type="checkbox" name="hobby[]" value="드라이브"></label>
<label>등산<input type="checkbox" name="hobby[]" value="등산"></label>
<label>게임<input type="checkbox" name="hobby[]" value="게임"></label>
<label>영화감상<input type="checkbox" name="hobby[]" value="영화감상"></label>
<label>쇼핑<input type="checkbox" name="hobby[]" value="쇼핑"></label>
</p>
<p>주민등록번호 :
<input type="text" name="ssn1" id="ssn1" maxlength="6" onkeyup="moveFocus()"> - <input type="text" name="ssn2" id="ssn2" maxlength="7">
<input type="button" value="주민등록번호 검증" onclick="ssnCheck()">
</p>
<p>우편번호 : <input type="text" name="zipcode" id="sample6_postcode"> <input type="button" value="우편번호 검색" onclick="sample6_execDaumPostcode()"></p>
<p><label>주소 : <input type="text" name="address1" id="sample6_address"></label></p>
<p><label>상세주소 : <input type="text" name="address2" id="sample6_detailAddress"></label></p>
<p><label>참고항목 : <input type="text" name="address3" id="sample6_extraAddress"></label></p>
<p><input type="submit" value="가입완료"> <input type="reset" value="다시작성">
<input type="button" value="로그인" onclick="location.href='./login.php'"></p>
</form>
</body>
</html>
** js/regist.js
'use strict';
function sendit(){
const userid = document.getElementById('userid');
const isIdCheck = document.getElementById('isIdCheck');
const userpw = document.getElementById('userpw');
const userpw_re = document.getElementById('userpw_re');
const username = document.getElementById('username');
const hp = document.getElementById('hp');
const email = document.getElementById('email');
const isSSN = document.getElementById('isSSN');
// 정규식
const expPwText = /^.*(?=^.{4,20}$)(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*()+=]).*$/;
const expNametext = /[가-힣]+$/;
const expHpText = /^\d{3}-\d{3,4}-\d{4}$/;
const expEmailText = /^[A-Za-z0-9\.\-]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\.\-]+$/;
if(userid.value == ''){
alert('아이디를 입력하세요.');
userid.focus();
return false;
}
if(userid.value.length < 4 || userid.value.length > 20){
alert('아이디를 4자이상 20자 이하로 입력하세요.');
userid.focus();
return false;
}
if(isIdCheck.value == 'false'){
alert('아이디 중복체크를 확인하세요.');
userid.focus();
return false;
}
if(userpw.value == ''){
alert('비밀번호를 입력하세요.');
userpw.focus();
return false;
}
if(expPwText.test(userpw.value) == false){
alert('비밀번호 형식을 확인하세요.')
userpw.focus();
return false;
}
if(userpw.value != userpw_re.value){
alert('비밀번호 비밀번호 확인의 값이 서로 다릅니다.');
userpw.focus();
return false;
}
if(expNametext.test(username.value) == false){
alert('이름 형식을 확인하세요.');
username.focus();
return false;
}
if(expHpText.test(hp.value) == false){
alert('휴대폰 번호 형식을 확인하세요.');
hp.focus();
return false;
}
if(expEmailText.test(email.value) == false){
alert('이메일 형식을 확인하세요.');
email.focus();
return false;
}
let isHobbycheck = false;
for(let i=0; i<$("[name='hobby[]']").length; i++){
if($("input:checkbox[name='hobby[]']").eq(i).is(":checked") == true){
isHobbycheck = true;
break;
}
}
if(!isHobbycheck){
alert("취미는 한개이상 체크하세요.");
return false;
}
if(isSSN.value == 'false'){
alert('주민등록번호 검증을 확인하세요.');
ssn1.focus();
return false;
}
}
function moveFocus(){
const ssn1 = document.getElementById('ssn1');
if(ssn1.value.length >= 6){
document.getElementById('ssn2').focus();
}
}
function ssnCheck(){
const ssn1 = document.getElementById('ssn1');
const ssn2 = document.getElementById('ssn2');
const isSSN = document.getElementById('isSSN');
if(ssn1.value == "" || ssn2.value == ""){
alert('주민등록번호를 입력하세요.');
ssn1.focus();
return false;
}
const ssn = ssn1.value + ssn2.value;
const s1 = Number(ssn.substr(0, 1)) * 2;
const s2 = Number(ssn.substr(1, 1)) * 3;
const s3 = Number(ssn.substr(2, 1)) * 4;
const s4 = Number(ssn.substr(3, 1)) * 5;
const s5 = Number(ssn.substr(4, 1)) * 6;
const s6 = Number(ssn.substr(5, 1)) * 7;
const s7 = Number(ssn.substr(6, 1)) * 8;
const s8 = Number(ssn.substr(7, 1)) * 9;
const s9 = Number(ssn.substr(8, 1)) * 2;
const s10 = Number(ssn.substr(9, 1)) * 3;
const s11 = Number(ssn.substr(10, 1)) * 4;
const s12 = Number(ssn.substr(11, 1)) * 5;
const s13 = Number(ssn.substr(12, 1));
let result = s1+s2+s3+s4+s5+s6+s7+s8+s9+s10+s11+s12;
result = result % 11;
result = 11 - result;
if(result >= 10) result = result % 10;
if(result == s13){
alert('유효한 주민등록번호입니다.');
isSSN.value = 'true';
}else{
alert('유효하지 않은 주민등록번호입니다.');
}
}
function idRegCheck() {
const userid = document.getElementById('userid');
//alert(userid.value);
if(userid.value == "") {
alert('아이디를 입력하세요.');
userid.focus();
return false;
}
const httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState == XMLHttpRequest.DONE && httpRequest.status == 200) {
//alert(httpRequest.responseText.trim());
if(httpRequest.responseText.trim() == "n") {
document.getElementById("idRegCheck_text").innerHTML = "사용할 수 있는 아이디입니다.";
isIdCheck.value = "true";
} else {
document.getElementById("idRegCheck_text").innerHTML = "사용할 수 없는 아이디입니다.";
}
}
};
httpRequest.open("GET", "idRegCheck_ok.php?mem_userid=" + userid.value, true);
httpRequest.send();
}
function isIdChange() {
document.getElementById("idRegCheck_text").innerHTML = "";
isIdCheck.value = "false";
}
** isRegCheck_ok.php
<?php
include "./include/dbconn.php";
$mem_userid = $_GET['mem_userid'];
if(!$conn) {
echo "연결 객체 생성 실패!";
} else {
$sql = "SELECT mem_idx FROM tb_member WHERE mem_userid='$mem_userid'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
if($row['mem_idx']) {
echo "y"; // 아이디 있음
} else {
echo "n"; // 아이디가 없음
}
}
?>
** 중복 검사 후 아이디 사용 가능이 판정되고 값을 변경하면 문제가 생긴다.
따라서 값이 변동되면 다시 중복 검사가 될 수 있도록 코드상 조치를 취해야 한다!
└ onkeyup나 onchange 이용하면 된다!!
9. 추천수
** view.php
<?php
session_start();
include "../include/dbconn.php";
$b_idx = $_GET['b_idx'];
$sql = "UPDATE tb_board SET b_hit = b_hit + 1 WHERE b_idx=$b_idx";
$result = mysqli_query($conn, $sql);
$sql = "SELECT * FROM tb_board WHERE b_idx=$b_idx";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$id = $_SESSION['id']; // 세션 아이디
$b_userid = $row['b_userid']; // 글쓴이 아이디
$b_title = $row['b_title'];
$b_content = $row['b_content'];
$b_hit = $row['b_hit'];
$b_regdate = $row['b_regdate'];
$b_up = $row['b_up'];
$b_file = $row['b_file'];
$imgpath = "";
if($row['b_file'] != "") {
$imgpath = "<img src='".$b_file."' width='200' alt='file'>";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글보기</title>
<script>
function up() {
const httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState == XMLHttpRequest.DONE && httpRequest.status == 200) {
alert('추천되었습니다.')
document.getElementById("up").innerHTML = httpRequest.responseText;
}
};
httpRequest.open("GET", "up_ok.php?b_idx=<?=$b_idx?>", true);
httpRequest.send();
}
</script>
</head>
<body>
<h2>글보기</h2>
<p><b>글쓴이</b> : <?=$b_userid?></p>
<p><b>날짜</b> : <?=$b_regdate?></p>
<p><b>조회수</b> : <?=$b_hit?></p>
<p><b>추천수</b> : <span id="up"><?=$b_up?></span></p>
<p><b>제목</b> : <?=$b_title?></p>
<p><b>내용</b></p>
<p><?=$b_content?></p>
<p><?=$imgpath?></p>
<p><input type="button" value="리스트" onclick="location.href='./list.php'">
<?php
if($id == $b_userid) {
?>
<input type="button" value="수정" onclick="location.href='./edit.php?b_idx=<?=$b_idx?>'">
<input type="button" value="삭제" onclick="location.href='./delete.php?b_idx=<?=$b_idx?>'">
<?php
}
?>
<img src='../images/up.png' alt="추천" onclick="up()">
</p>
<form name="reform" method="post" action="reply_ok.php">
<input type="hidden" name="b_idx" value="<?=$b_idx?>">
<p><?=$id?> : <input type="text" name="re_content"> <input type="submit" value="댓글달기"></p>
</form>
<hr>
<?php
$sql = "SELECT * FROM tb_reply WHERE re_board_idx='$b_idx' ORDER BY re_idx DESC";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)) {
$re_idx = $row['re_idx'];
$re_userid = $row['re_userid'];
$re_content = $row['re_content'];
$re_regdate = $row['re_regdate'];
$re_board_idx = $row['re_board_idx']
?>
<p><?=$re_userid?> - <?=$re_content?> (<?=$re_regdate?>)
<?php
if($id == $re_userid) {
?>
<input type="button" value="삭제"
onclick="location.href='reply_del.php?re_board_idx=<?=$re_board_idx?>&re_idx=<?=$re_idx?>'"></p>
<?php
}
}
?>
</body>
</html>
** up_ok.php
<?php
include "../include/dbconn.php";
$b_idx = $_GET['b_idx'];
if(!$conn) {
echo "연결 객체 생성 실패!";
} else {
$sql = "UPDATE tb_board SET b_up=b_up + 1 WHERE b_idx='$b_idx'";
$result = mysqli_query($conn, $sql);
$sql = "SELECT b_up FROM tb_board WHERE b_idx='$b_idx'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row['b_up'];
}
?>
10. 세션 처리
** modify.php
<?php
session_start();
include "./include/dbconn.php";
if(!isset($_SESSION['idx'])) {
echo "<script>alert('잘못된 접근입니다. 로그인하세요.'); location.href='./login.php';</script>";
}
$idx = $_SESSION['idx'];
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$sql = "SELECT * FROM tb_member WHERE mem_idx = $idx";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$mem_email = $row['mem_email'];
$mem_ssn1 = $row['mem_ssh1'];
$mem_ssn2 = $row['mem_ssh2'];
$mem_hp = $row['mem_hp'];
$mem_hobby = $row['mem_hobby'];
$hobbyarr = explode(",", $mem_hobby);
$mem_zipcode = $row['mem_zipcode'];
$mem_address1 = $row['mem_address1'];
$mem_address2 = $row['mem_address2'];
$mem_address3 = $row['mem_address3'];
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>회원 정보 수정</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="./js/modify.js"></script>
<script src="https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
function sample6_execDaumPostcode() {
new daum.Postcode({
oncomplete: function(data) {
// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
// 각 주소의 노출 규칙에 따라 주소를 조합한다.
// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
var addr = ''; // 주소 변수
var extraAddr = ''; // 참고항목 변수
//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
addr = data.roadAddress;
} else { // 사용자가 지번 주소를 선택했을 경우(J)
addr = data.jibunAddress;
}
// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
if(data.userSelectedType === 'R'){
// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraAddr += data.bname;
}
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraAddr !== ''){
extraAddr = ' (' + extraAddr + ')';
}
// 조합된 참고항목을 해당 필드에 넣는다.
document.getElementById("sample6_extraAddress").value = extraAddr;
} else {
document.getElementById("sample6_extraAddress").value = '';
}
// 우편번호와 주소 정보를 해당 필드에 넣는다.
document.getElementById('sample6_postcode').value = data.zonecode;
document.getElementById("sample6_address").value = addr;
// 커서를 상세주소 필드로 이동한다.
document.getElementById("sample6_detailAddress").focus();
}
}).open();
}
</script>
</head>
<body>
<h2>회원 정보 수정</h2>
<form name="regform" id="regform" method="post" action="modify_ok.php" onsubmit="return sendit()">
<input type="hidden" name="isSsn" id="isSsn" value="false">
<p>아이디 : <b><?=$id?></b></p>
<p><label>비밀번호 : <input type="password" name="userpw" id="userpw" maxlength="20"></label></p>
<p><label>비밀번호 확인 : <input type="password" name="userpw_re" id="userpw_re" maxlength="20"></label></p>
<p>이름 : <b><?=$name?></b></p>
<p><label>휴대폰 번호 : <input type="text" name="hp" id="hp" value="<?=$mem_hp?>"></label> ('-' 을 포함)</p>
<p><label>이메일 : <input type="text" name="email" id="email" value="<?=$mem_email?>"></label></p>
<p>취미 :
<label>드라이브<input type="checkbox" name="hobby[]" value="드라이브"
<?php if(in_array("드라이브", $hobbyarr)) { ?> checked <?php } ?>></label>
<label>등산<input type="checkbox" name="hobby[]" value="등산"
<?php if(in_array("등산", $hobbyarr)) { echo " checked "; } ?>></label>
<label>게임<input type="checkbox" name="hobby[]" value="게임"
<?php if(in_array("게임", $hobbyarr)) { echo " checked "; } ?>></label>
<label>영화감상<input type="checkbox" name="hobby[]" value="영화감상"
<?php if(in_array("영화감상", $hobbyarr)) { echo " checked "; } ?>></label>
<label>쇼핑<input type="checkbox" name="hobby[]" value="쇼핑"
<?php if(in_array("쇼핑", $hobbyarr)) { echo " checked "; } ?>></label>
</p>
<p>주민등록번호 :
<input type="text" name="ssn1" id="ssn1" maxlength="6" value="<?=$mem_ssn1?>" onkeyup="moveFocus()"> -
<input type="text" name="ssn2" id="ssn2" maxlength="7" value="<?=$mem_ssn2?>">
<input type="button" value="주민등록번호 검증" onclick="ssnCheck()">
</p>
<p>우편번호 : <input type="text" name="zipcode" id="sample6_postcode" value="<?=$mem_zipcode?>"> <input type="button" value="우편번호 검색" onclick="sample6_execDaumPostcode()"></p>
<p><label>주소 : <input type="text" name="address1" id="sample6_address" value="<?=$mem_address1?>"></label></p>
<p><label>상세주소 : <input type="text" name="address2" id="sample6_detailAddress" value="<?=$mem_address2?>"></label></p>
<p><label>참고항목 : <input type="text" name="address3" id="sample6_extraAddress" value="<?=$mem_address3?>"></label></p>
<p><input type="submit" value="수정완료"> <input type="reset" value="다시작성"> <input type="button" value="돌아가기" onclick="location.href='./login.php'"></p>
</form>
</body>
</html>
** include/sessionCheck.php
<?php
if(!isset($_SESSION['idx'])) {
echo "<script>alert('잘못된 접근입니다. 로그인하세요.'); location.href='../login.php';</script>";
}
?>
** board/write.php
<?php
session_start();
include "../include/sessionCheck.php";
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글쓰기</title>
</head>
<body>
<h2>글쓰기</h2>
<form method="post" action="write_ok.php" enctype="multipart/form-data">
<p><label>아이디 : <?=$_SESSION['id']?></label></p>
<p><label>제목 : <input type="text" name="b_title"></label></p>
<p>내용</p>
<p><textarea cols="40" rows="6" name="b_content"></textarea></p>
<p>파일 : <input type="file" name="b_file"></p>
<p><input type="submit" value="확인">
<input type="reset" value="다시작성">
<input type="button" value="리스트" onclick="location.href='./list.php'"></p>
</form>
</body>
</html>
** write_ok.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$id = $_SESSION['id'];
$b_title = $_POST['b_title'];
$b_content = $_POST['b_content'];
$filepath = "";
if($_FILES['b_file']['tmp_name']) {
$uploads_dir = './upload';
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
$error = $_FILES['b_file']['error'];
$name = $_FILES['b_file']['name']; // apple.jpg
$ext = explode(".", $name); // ext[0] = "apple", ext[1] = "jpg"
$rename = $ext[0].time();
$rename = $rename.".".$ext[1];
$ext = strtolower(array_pop($ext)); // array_pop() : 스택구조,
// 마지막 값을 뽑아내고 그 값을 반환한다.
// 해당 데이터는 array에서 사라진다.
if($error != UPLOAD_ERR_OK) { // UPLOAD_ERR_OK(0) -> 오류 없이 파일 업로드 성공
switch($error) {
case UPLOAD_ERR_INI_SIZE: // php.ini에 설정된 최대 파일을 초과
case UPLOAD_ERR_FORM_SIZE: // HTML 폼에 설정된 최대 파일을 초과
echo "파일 크기가 너무 큽니다.";
break;
case UPLOAD_ERR_NO_FILE: // 파일이 제대로 업로드 되지 않았을 경우
echo "파일이 제대로 첨부되지 않았습니다.";
break;
default:
echo "파일 업로드 실패";
}
exit;
}
if(!in_array($ext, $allowed_ext)) {
echo "허용되지 않은 확장명입니다.";
exit;
}
$filepath = $uploads_dir."/".$rename;
move_uploaded_file($_FILES['b_file']['tmp_name'], $filepath);
}
$sql = "INSERT INTO tb_board (b_userid, b_title, b_content, b_file) VALUES ('$id', '$b_title', '$b_content', '$filepath')";
$result = mysqli_query($conn, $sql);
echo "<script>alert('저장되었습니다.');location.href='list.php';</script>"
?>
** view.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$b_idx = $_GET['b_idx'];
$sql = "UPDATE tb_board SET b_hit = b_hit + 1 WHERE b_idx=$b_idx";
$result = mysqli_query($conn, $sql);
$sql = "SELECT * FROM tb_board WHERE b_idx=$b_idx";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$id = $_SESSION['id']; // 세션 아이디
$b_userid = $row['b_userid']; // 글쓴이 아이디
$b_title = $row['b_title'];
$b_content = $row['b_content'];
$b_hit = $row['b_hit'];
$b_regdate = $row['b_regdate'];
$b_up = $row['b_up'];
$b_file = $row['b_file'];
$imgpath = "";
if($row['b_file'] != "") {
$imgpath = "<img src='".$b_file."' width='200' alt='file'>";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글보기</title>
<script>
function up() {
const httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState == XMLHttpRequest.DONE && httpRequest.status == 200) {
alert('추천되었습니다.')
document.getElementById("up").innerHTML = httpRequest.responseText;
}
};
httpRequest.open("GET", "up_ok.php?b_idx=<?=$b_idx?>", true);
httpRequest.send();
}
</script>
</head>
<body>
<h2>글보기</h2>
<p><b>글쓴이</b> : <?=$b_userid?></p>
<p><b>날짜</b> : <?=$b_regdate?></p>
<p><b>조회수</b> : <?=$b_hit?></p>
<p><b>추천수</b> : <span id="up"><?=$b_up?></span></p>
<p><b>제목</b> : <?=$b_title?></p>
<p><b>내용</b></p>
<p><?=$b_content?></p>
<p><?=$imgpath?></p>
<p><input type="button" value="리스트" onclick="location.href='./list.php'">
<?php
if($id == $b_userid) {
?>
<input type="button" value="수정" onclick="location.href='./edit.php?b_idx=<?=$b_idx?>'">
<input type="button" value="삭제" onclick="location.href='./delete.php?b_idx=<?=$b_idx?>'">
<?php
}
?>
<img src='../images/up.png' alt="추천" onclick="up()">
</p>
<form name="reform" method="post" action="reply_ok.php">
<input type="hidden" name="b_idx" value="<?=$b_idx?>">
<p><?=$id?> : <input type="text" name="re_content"> <input type="submit" value="댓글달기"></p>
</form>
<hr>
<?php
$sql = "SELECT * FROM tb_reply WHERE re_board_idx='$b_idx' ORDER BY re_idx DESC";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)) {
$re_idx = $row['re_idx'];
$re_userid = $row['re_userid'];
$re_content = $row['re_content'];
$re_regdate = $row['re_regdate'];
$re_board_idx = $row['re_board_idx']
?>
<p><?=$re_userid?> - <?=$re_content?> (<?=$re_regdate?>)
<?php
if($id == $re_userid) {
?>
<input type="button" value="삭제"
onclick="location.href='reply_del.php?re_board_idx=<?=$re_board_idx?>&re_idx=<?=$re_idx?>'"></p>
<?php
}
}
?>
</body>
</html>
** up_ok.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$b_idx = $_GET['b_idx'];
if(!$conn) {
echo "연결 객체 생성 실패!";
} else {
$sql = "UPDATE tb_board SET b_up=b_up + 1 WHERE b_idx='$b_idx'";
$result = mysqli_query($conn, $sql);
$sql = "SELECT b_up FROM tb_board WHERE b_idx='$b_idx'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row['b_up'];
}
?>
** reply_ok.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$id = $_SESSION['id'];
$re_content = $_POST['re_content'];
$b_idx = $_POST['b_idx'];
$sql = "INSERT INTO tb_reply(re_userid, re_content, re_board_idx) VALUES ('$id', '$re_content', '$b_idx')";
$result = mysqli_query($conn, $sql);
echo "<script>alert('저장되었습니다.');location.href='view.php?b_idx=".$b_idx."'</script>";
?>
** reply_del.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$re_board_idx = $_GET['re_board_idx'];
$re_idx = $_GET['re_idx'];
$sql = "DELETE FROM tb_reply WHERE re_idx='$re_idx'";
$result = mysqli_query($conn, $sql);
echo "<script>alert('삭제되었습니다.');location.href='view.php?b_idx=".$re_board_idx."';</script>";
?>
** list.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$sql = "SELECT * FROM tb_board ORDER BY b_idx DESC";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>리스트</title>
</head>
<body>
<h2>리스트</h2>
<table border="1" width="800">
<tr>
<th>번호</th>
<th>제목</th>
<th>글쓴이</th>
<th>조회수</th>
<th>날짜</th>
<th>추천수</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
$b_idx = $row['b_idx'];
$b_userid = $row['b_userid'];
$b_title = $row['b_title'];
$b_hit = $row['b_hit'];
$b_regdate = $row['b_regdate'];
$b_up = $row['b_up'];
$b_file = $row['b_file'];
$imgpath = "";
if($row['b_file'] != "") {
$imgpath = "<img src='../images/file.png' width='16' alt='file'>";
}
?>
<tr>
<td><?=$b_idx?></td>
<td><a href="./view.php?b_idx=<?=$b_idx?>"><?=$b_title?></a><?=$imgpath?></td>
<td><?=$b_userid?></td>
<td><?=$b_hit?></td>
<td><?=$b_regdate?></td>
<td><?=$b_up?></td>
</tr>
<?php
}
?>
</table>
<p><input type="button" value="글쓰기" onclick="location.href='./write.php'">
<input type="button" value="돌아가기" onclick="location.href='../login.php'"></p>
</body>
</html>
** edit.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$b_idx = $_GET['b_idx'];
$sql = "SELECT * FROM tb_board WHERE b_idx=$b_idx";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$b_title = $row['b_title'];
$b_content = $row['b_content'];
$b_file = $row['b_file'];
$imgpath = "";
if($row['b_file'] != "") {
$imgpath = "<img src='".$b_file."' width='200' alt='file'>";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>글수정</title>
</head>
<body>
<h2>글수정</h2>
<form method="post" action="edit_ok.php" enctype="multipart/form-data">
<input type="hidden" name="b_idx" value="<?=$b_idx?>">
<p><label>아이디 : <?=$_SESSION['id']?></label></p>
<p><label>제목 : <input type="text" name="b_title" value="<?=$b_title?>"></label></p>
<p>내용</p>
<p><textarea cols="40" rows="6" name="b_content"><?=$b_content?></textarea></p>
<p>파일 : <input type="file" name="b_file"></p>
<p><?=$imgpath?></p>
<p><input type="submit" value="확인"> <input type="reset" value="다시작성">
<input type="button" value="리스트" onclick="location.href='./list.php'"></p>
</form>
</body>
</html>
** edit_ok.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$b_idx = $_POST['b_idx'];
$b_title = $_POST['b_title'];
$b_content = $_POST['b_content'];
$filepath = "";
if($_FILES['b_file']['tmp_name']) {
$uploads_dir = './upload';
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
$error = $_FILES['b_file']['error'];
$name = $_FILES['b_file']['name'];
$ext = explode(".", $name);
$rename = $ext[0].time();
$rename = $rename.".".$ext[1];
$ext = strtolower(array_pop($ext));
if($error != UPLOAD_ERR_OK) {
switch($error) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
echo "파일 크기가 너무 큽니다.";
break;
case UPLOAD_ERR_NO_FILE:
echo "파일이 제대로 첨부되지 않았습니다.";
break;
default:
echo "파일 업로드 실패";
}
exit;
}
if(!in_array($ext, $allowed_ext)) {
echo "허용되지 않은 확장명입니다.";
exit;
}
$filepath = $uploads_dir."/".$rename;
move_uploaded_file($_FILES['b_file']['tmp_name'], $filepath);
// 첨부파일이 있을때
$sql = "UPDATE tb_board SET b_title='$b_title', b_content='$b_content', b_file='$filepath' WHERE b_idx=$b_idx";
} else {
// 첨부파일이 없을때
$sql = "UPDATE tb_board SET b_title='$b_title', b_content='$b_content' WHERE b_idx=$b_idx";
}
$result = mysqli_query($conn, $sql);
echo "<script>alert('수정되었습니다.');location.href='view.php?b_idx=".$b_idx."';</script>"
?>
** delete.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$b_idx = $_GET['b_idx'];
$sql = "DELETE FROM tb_board WHERE b_idx=$b_idx";
$result = mysqli_query($conn, $sql);
echo "<script>alert('삭제되었습니다.');location.href='list.php';</script>";
?>
11. 페이징 처리
[전체] SELECT * FROM tb_board ORDER BY b_idx DESC;
[1page] SELECT * FROM tb_board ORDER BY b_idx DESC LIMIT ((1 - 1) * 3), 3;
[2page] SELECT * FROM tb_board ORDER BY b_idx DESC LIMIT ((2 - 1) * 3), 3;
[3page] SELECT * FROM tb_board ORDER BY b_idx DESC LIMIT ((3 - 1) * 3), 3;
[4page] SELECT * FROM tb_board ORDER BY b_idx DESC LIMIT ((4 - 1) * 3), 3;
** list.php
<?php
session_start();
include "../include/dbconn.php";
include "../include/sessionCheck.php";
$sql = "SELECT * FROM tb_board ORDER BY b_idx DESC";
$result = mysqli_query($conn, $sql);
$pageNum = 3;
$pageTotal = $result->num_rows;
$start = 0;
if(isset($_GET['start'])) {
$start = $_GET['start'];
}
$sql = "SELECT * FROM tb_board ORDER BY b_idx DESC LIMIT $start, $pageNum";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>리스트</title>
</head>
<body>
<h2>리스트</h2>
<p>전체 게시물 : <?=$pageTotal?></p>
<table border="1" width="800">
<tr>
<th>번호</th>
<th>제목</th>
<th>글쓴이</th>
<th>조회수</th>
<th>날짜</th>
<th>추천수</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
$b_idx = $row['b_idx'];
$b_userid = $row['b_userid'];
$b_title = $row['b_title'];
$b_hit = $row['b_hit'];
$b_regdate = $row['b_regdate'];
$b_up = $row['b_up'];
$b_file = $row['b_file'];
$imgpath = "";
if($row['b_file'] != "") {
$imgpath = "<img src='../images/file.png' width='16' alt='file'>";
}
?>
<tr>
<td><?=$b_idx?></td>
<td><a href="./view.php?b_idx=<?=$b_idx?>"><?=$b_title?></a><?=$imgpath?></td>
<td><?=$b_userid?></td>
<td><?=$b_hit?></td>
<td><?=$b_regdate?></td>
<td><?=$b_up?></td>
</tr>
<?php
}
?>
</table>
<p>
<?php
$pages = $pageTotal / $pageNum;
for($i=0; $i<$pages; $i++) {
$nextPage = $pageNum * $i;
echo "<a href=$_SERVER[PHP_SELF]?start=$nextPage>[".($i + 1)."]</a>";
}
?>
</p>
<p><input type="button" value="글쓰기" onclick="location.href='./write.php'">
<input type="button" value="돌아가기" onclick="location.href='../login.php'"></p>
</body>
</html>
'웹_프론트_백엔드 > 프론트엔드' 카테고리의 다른 글
2021.02.21 (0) | 2021.02.21 |
---|---|
2021.02.20 (0) | 2021.02.21 |
2021.02.06 (0) | 2021.02.06 |
2021.01.31 (0) | 2021.01.31 |
2021.01.30 (0) | 2021.01.30 |