수정

[update_write.php]

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
<?php
    session_start();    //session 가져오기
    //session에 데이터가 없다면 로그인 화면으로 GO
    if (!isset($_SESSION['userID'])) {
        header('Location : http://wamp서버ip주소:80/test/login/login');
    }
 
    $idx = $_GET['idx'];
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="/test/js/bootstrap.js"></script>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>글 수정하기</title>
        <link rel ="stylesheet" href="/test/css/bootstrap.css">
    </head>
    <!--php에서 html로 변수 가져오는 방법-->
    <input type ="hidden" id = "index1" value="<?=$idx?>">
    <script>
        $(document).ready(function(){
            $('#form_data').submit(function(e){
                e.preventDefault();
                $.ajax({
                    type : 'POST',
                    url : 'http://wamp서버ip주소:80/test/notice_board/update',
                    // serialize()뒤에 데이터 붙이는 방법
                    data : $(this).serialize() + "&index="+$('#index1').val(),
                    success : function(result){
                        if(result=="success"){
                            alert("글 수정 성공");
                            location.replace('http://wamp서버ip주소:80/test/main')
                        }else if(result=="Fail:save"){
                            alert("글 수정 실패...다시 시도 해주세요.");
                        }else if(result=="Fail:title"){
                            alert("제목이 없습니다. 제목을 입력하세요.");
                        }else if(result=="Fail:contents"){
                            alert("글 내용이 없습니다. 글 내용을 입력하세요.");
                        }
                    },
                    error : function(xtr,status,error){
                    alert(xtr +":"+status+":"+error);
                    }
                });
            });
        });
    </script>
    <body>
        <div class ="container">
            <form id ="form_data" method ="POST">
                <table class ="table table-bordered">
                    <thead>
                        <caption>글 수정하기</caption>
                    </thead>
                    <tbody>
                        <tr>
                            <th>제목 : </th>
                            <td><input type ="text" name = "title" id = "title" class="form-control" placeholder = "Enter your Title"></td>
                        </tr>
                        <tr>    
                            <th>작성자 : </th>
                            <td><?php echo $_SESSION['userNAME'];?></td>
                        </tr>
                        <tr>
                            <th>내용 : </th>
                            <td><textarea cols="10" name = "contents" id = "contents" class="form-control" placeholder = "Enter your Contents"></textarea></td>
                        </tr>
                    </tbody>
                </table>  
                <input type = "submit" class="btn btn-outline-primary" value = "저장하기">
            </form>
        </div>
    </body>
</html>
 
 

[update.php]

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
<?php
    include "../connect_db.php";
 
    session_start();
 
    $title = $_POST['title'];
    $contents = $_POST['contents'];
    $name = $_SESSION['userNAME'];
    $index = $_POST['index'];
 
    // 제목하고 글 내용이 비어있는지 확인 후 insert 쿼리 실행
    if($title == NULL){
        echo "Fail:title";
    }else if($contents == NULL){
        echo "Fail:contents";
    }else{
        $datetime = date_create()->format('Y-m-d H:i:s');
        $sql = "UPDATE board SET title = '$title', contents = '$contents' WHERE idx ='$index'";
 
        $result = $db->query($sql);
        if($result){
            echo "success";
        }else{
            echo "Fail:save";
        }
    }
?>
 
 

글 번호 19번 / 제목 게시판 만들기 테스트

글 번호 19번 / 제목 게시판 만들기 테스트 ---------> 수정하기 테스트로 바뀜

데이터베이스 확인


삭제

[delete.php]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
    include "../connect_db.php";
    
    session_start();
 
    //read.php에서 삭제하고자 하는 글 번호 받기
    $index = $_POST['idx'];
 
    //삭제 쿼리 문 실행
    $sql = "DELETE FROM board WHERE idx ='$index'";
    $result = $db->query($sql);
 
    // 성공,실패 리턴
    if($result){
        echo "success";
    }else{
        echo "Fail:delete";
    }
?>
 

글 삭제 후 main 페이지로 이동됨

데이터베이스에서 19번 글이 사라진걸 확인 할 수 있다.

[main]화면에서 18번 글 의 조회수는 1

제목을 클릭하면 해당 글 읽기 가 되고 조회수가 올라간다.

글 쓰기 버튼을 누르면 글쓰기 화면으로 전환된다.

우선 읽기부터....


[read.php]

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
89
90
91
92
93
94
95
96
97
98
<?php
    include "../connect_db.php";
 
    session_start();    //session 가져오기
    //session에 데이터가 없다면 로그인 화면으로 GO
    if (!isset($_SESSION['userID'])) {
        header('Location : http://wamp서버ip주소:80/test/login/login');
    }
 
    // main.php에서 넘어온 글 번호 값
    $index=$_GET['idx'];
    
    // 조회 수 증가
    $increase_sql = "UPDATE board SET views = views+1 WHERE idx ='$index'";
    $increase_result = $db->query($increase_sql);
 
    // 해당 글을 읽어오기 위한 쿼리문..
    $sql = "SELECT * FROM board WHERE idx='$index'";
    $result = $db->query($sql);
    $data = $result->fetch_array(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="/test/js/bootstrap.js"></script>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>글 읽기</title>
        <link rel ="stylesheet" href="/test/css/bootstrap.css">
    </head>
    <!--php의 변수 html로 가져오기-->
    <input type="hidden" id="d1" value="<?=$index?>">
    <!--삭제를 위한 스크립트-->
    <script>
        $(document).ready(function(){
            //삭제 버튼 클릭시
            $('#delete_btn').click(function(){
                $.ajax({
                    type : 'POST',
                    url : 'http://192.168.0.2:80/test/notice_board/delete',
                    data : {
                        idx : $("#d1").val()
                    },
                    success : function(result){
                        if(result=="success"){
                            alert("글 삭제 성공");
                            location.replace('http://wamp서버ip주소:80/test/main');
                        }else if(result=="Fail:delete"){
                            alert("글 삭제 실패...다시 시도 해주세요.");
                        }
                    },
                    error : function(xtr,status,error){
                        alert(xtr +":"+status+":"+error);
                    }
                });
            });
        });
    </script>
    <body>
        <div class ="container">
            <table class ="table table-bordered">
                <thead>
                    <caption>글 읽기</caption>
                </thead>
                <tbody>
                    <tr>
                        <th>제목 : </th>
                        <td><?php echo $data['title'];?></td>
                    </tr>
                    <tr>
                        <th>작성 일자 : </th>
                        <td><?php echo $data['date'];?></td>
                    </tr>
                    <tr>
                        <th>조회수 : </th>
                        <td><?php echo $data['views'];?></td>
                    </tr>
                    <tr>    
                        <th>작성자 : </th>
                        <td><?php echo $data['author'];?></td>
                    </tr>
                    <tr>
                        <th>내용 : </th>
                        <td><?php echo $data['contents'];?></td>
                    </tr>
                </tbody>
            </table>
            <!--본인이 작성한 글이라면 수정,삭제 버튼 보이기-->
            <?php
                if($_SESSION['userNAME']==$data['author']){
            ?>
                    <a class="btn btn-outline-primary" id ="update_btn" href ="/test/notice_board/update_write?idx=<?php echo $index;?>">수정하기</a>
                    <input type ="button" class="btn btn-outline-primary" id ="delete_btn" value="삭제하기">
            <?php } ?>
        </div>
    </body>
</html>
 

실행 화면(본인이 쓴 글이 아닌 경우) - 수정,삭제 버튼 안보임

조회수가 1증가된 2가 됨...

실행 화면(본인이 쓴 글 일 경우) - 수정,삭제 버튼 보임 


글 쓰기

[write.php]

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
<?php
    session_start();    //session 가져오기
    //session에 데이터가 없다면 로그인 화면으로 GO
    if (!isset($_SESSION['userID'])) {
        header('Location : http://wamp서버ip주소:80/test/login/login');
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="/test/js/bootstrap.js"></script>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>글쓰기</title>
        <link rel ="stylesheet" href="/test/css/bootstrap.css">
    </head>
    <script>
        $(document).ready(function(){
            $('#form_data').submit(function(e){
                e.preventDefault();
                $.ajax({
                    type : 'POST',
                    url : 'http://wamp서버ip주소:80/test/notice_board/insert',
                    data : $(this).serialize(),
                    success : function(result){
                        if(result=="success"){
                        alert("글 쓰기 저장 성공");
                        location.replace('http://wamp서버ip주소:80/test/main')
                        }else if(result=="Fail:save"){
                            alert("글 쓰기 저장 실패...다시 시도 해주세요.");
                        }else if(result=="Fail:title"){
                            alert("제목이 없습니다. 제목을 입력하세요.");
                        }else if(result=="Fail:contents"){
                            alert("글 내용이 없습니다. 글 내용을 입력하세요.");
                        }
                    },
                    error : function(xtr,status,error){
                    alert(xtr +":"+status+":"+error);
                    }
                });
            });
        });
    </script>
    <body>
        <div class ="container">
            <form id ="form_data" method ="POST">
                <table class ="table table-bordered">
                    <thead>
                        <caption>글 쓰기</caption>
                    </thead>
                    <tbody>
                        <tr>
                            <th>제목 : </th>
                            <td><input type ="text" name = "title" id = "title" class="form-control" placeholder = "Enter your Title"></td>
                        </tr>
                        <tr>    
                            <th>작성자 : </th>
                            <td><?php echo $_SESSION['userNAME'];?></td>
                        </tr>
                        <tr>
                            <th>내용 : </th>
                            <td><textarea cols="10" name = "contents" id = "contents" class="form-control" placeholder = "Enter your Contents"></textarea></td>
                        </tr>
                    </tbody>
                </table>  
                <input type = "submit" class="btn btn-outline-primary" value = "저장하기">
            </form>
        </div>
    </body>
</html>
 
 

[insert.php]

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
<?php
    include "../connect_db.php";
 
    session_start();
 
    $title = $_POST['title'];
    $contents = $_POST['contents'];
    $name = $_SESSION['userNAME'];
 
    // 제목하고 글 내용이 비어있는지 확인 후 insert 쿼리 실행
    if($title == NULL){
        echo "Fail:title";
    }else if($contents == NULL){
        echo "Fail:contents";
    }else{
        $datetime = date_create()->format('Y-m-d H:i:s');
        $sql = "INSERT INTO board VALUES (NULL,'$title','$name','$contents','$datetime',0)";
 
        $result = $db->query($sql);
        if($result){
            echo "success";
        }else{
            echo "Fail:save";
        }
    }
?>
 

실행 화면 

저장하기 버튼 클릭!!

글이 추가된 화면

데이터베이스 확인

로그인을 하면 session에 회원 아이디와 회원 이름이 저장된다.

이후 게시판을 이용할 때 회원의 아이디와 이름이 필요 할 때 마다 session에 저장된 아이디와 이름을 꺼내 쓸 수 있다.


데이터베이스 board 테이블 data


[connect_db.php]

1
2
3
4
5
6
7
8
9
<?php
//MYSQL 접속 정보
$db = mysqli_connect("127.0.0.1:3306","DB사용자명","DB비번","DB");
if(!$db){
    die("Error ".mysqli_connect_error());
}
//한글
mysqli_set_charset($db'UTF8');
?>
 
 

[main.php] - 로그인후 첫화면

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
89
90
<?php
    include "connect_db.php";
 
    session_start();    //session 가져오기
    //session에 데이터가 없다면 로그인 화면으로 GO
    if (!isset($_SESSION['userID'])) {
        header('Location : http://wamp서버ip:80/test/login/login');
    }
 
    //한 화면에 보여주는 글 목록 개수
    $page_size=5;
 
    //현재 페이지 기억
    if (isset($_GET["current_page"])) {
        $current_page = $_GET["current_page"];
    }else{
        $current_page=1;
    }
 
    //시작 페이지 정하기
    $begin = ($current_page -1* $page_size;
?>
<!DOCTYPE html>
<html>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="/test/js/bootstrap.js"></script>
    <head>
        <meta charset ="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>게시판 리스트</title>
        <link rel ="stylesheet" href="/test/css/bootstrap.css">
    </head>
    <body>
        <div class = "container">
            <table class = "table table-hover">
                <thead>
                    <tr>
                        <!--게시판 속성-->
                        <th>글번호</th>
                        <th>제목</th>
                        <th>작성자</th>
                        <th>날짜</th>
                        <th>조회수</th>
                    </tr>
                </thead>
                <?php       // DB에 저장된 글목록을 idx의 내림차순으로 가져와 페이지에 집어넣기
                $sql = "SELECT * FROM board ORDER BY idx DESC limit $begin,$page_size";
                $result = $db->query($sql);
                while($board=$result->fetch_array(MYSQLI_ASSOC)){
                    $title = $board['title'];
                    // 만약 title의 길이가 길면 중간을 '....'으로 표시
                    if(strlen($title)>15){ 
                        $title=str_replace($board["title"],mb_substr($board["title"],0,15,"UTF8")."...",$board["title"]); //title이 15을 넘어서면 ...표시
                    }
                ?>
                <tbody>
                    <tr>
                        <td><?php echo $board['idx'];?></td>
                        <!--제목 클릭시 게시글 읽기-->
                        <td><a href ="/test/notice_board/read?idx=<?php echo $board['idx']; ?>"><?php echo $title;?></td>
                        <td><?php echo $board['author'];?></td>
                        <td><?php echo $board['date'];?></td>
                        <td><?php echo $board['views'];?></td>
                    </tr>
                </tbody>
        <?php   } ?>    <!--while문 종료-->
            </table>
            <hr/>
            <a class="btn btn-outline-primary" href="/test/notice_board/write">글쓰기</a>
            <a class="btn btn-outline-primary" href="/test/login/logout">로그아웃</a>
        
        <!--페이지 번호-->
        <?php
            $page_sql = "SELECT COUNT(idx) FROM board";     // 글 목록 수 구하는 쿼리문
            $page_result = mysqli_query($db$page_sql);    // 쿼리문 실행
            $row = mysqli_fetch_row($page_result);          // 실행 값 열로 가져오기(데이터 접근하기 위해)
            $total_records = $row[0];                       // [0]번째에 저장되어 있으므로..
            $total_pages = ceil($total_records / $page_size);   // 페이지 수 구하기
        ?>
            <div class = "pagination justify-content-center">
            <ul class = 'pagination'>
                <?php
                    // 페이지 수만큼 페이지 버튼 만들고 해당 페이지 번호에 게시글 배정
                    for ($i=1$i<=$total_pages$i++) {
                        ?><li class='page-item'><a class='page-link' href='/test/main?current_page=<?php echo $i;?>'><?php echo $i;?></a></li>
                <?php } ?>
            </div>
        </div>
    </body>
</html>
 

실행 화면

3페이지로 이동

 

준비 : 서버 2대와 각각의 서버에 mysql 설치되어있는 상태

 

Master 서버 부분

1. mysql 환경 설정

[vi /etc/my.cnf]

1
2
3
4
[mysqld]
log-bin=mysql-bin
server-id=1
binlog_do_db=EdgeDB
 

 

2. mysql 계정 생성(slave에서 master로 접속할 계정)

1
mysql> grant all privileges on *.* to 'repl'@'%' identified by '';
 

 

3. systemctl restart mysqld

mysql 재시작

 

 

4. master 서버 정보 확인

1
2
3
4
5
6
7
 mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000002 |     1956 | EdgeDB       |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
 
 

여기서 file 이름과 position 위치를 알고 있어야 한다.

 


Slave 서버 부분

1. slave서버에 master에 있는 db명과 같은 디비 생성(만약 dump 파일로 db를 옮긴 상태라면 이 과정은 필요없다.)

1
 mysql> create database EdgeDB default character set utf8;
 

 

2. slave 서버 mysql 환경 설정

[vi /etc/my.cnf]

1
2
3
4
5
[mysqld]
server-id=2
binlog_do_db=EdgeDB
slave-skip-errors=all
read_only=1
 

 

3. systemctl restart mysqld

mysql 재시작

 

 

4. slave 서버의 mysql 내부 설정

1
2
3
4
5
6
mysql> change master to
master_host='마스터ip주소',
master_user='repl',
master_password='repl의 비번',
master_log_file='mysql-bin.000002',
master_log_pos=1956;
 

 


5. 연결 확인(master)

1
2
3
4
5
6
7
8
9
10
mysql> show processlist\G
*************************** 1. row ***************************
     Id: 106
   User: repl
   Host: slave서버ip:50896
     db: NULL
Command: Binlog Dump
   Time: 3537
  State: Master has sent all binlog to slave; waiting for more updates
   Info: NULL
 
 

6 slave 서버에서...

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
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: master ip주소
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 1956
               Relay_Log_File: mysqld-relay-bin.000002
                Relay_Log_Pos: 1740
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1956
              Relay_Log_Space: 1914
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: b9ea7ac5-207f-11e9-b5f6-1866da603378
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
1 row in set (0.00 sec)
 
 

Last_IO_Errno: 0

Last_IO_Error:

위와 같이 에러 내용이 없어야 한다.

 

실제로 마스터 mysql에서 데이터를 입출력 하면 slave에 데이터가 입출력 되는것을 확인 가능하다.

'Centos7 > MySQL' 카테고리의 다른 글

GROUP BY 그룹별-월별 최신날짜의 데이터 가져오기  (0) 2020.06.29
MySQL Replication 작동 원리  (0) 2019.05.16

로그인 기능에 이어 회원가입 기능을 추가 해봅니다.

 

로그인 페이지에서 회원가입 페이지로 넘어가면..아래와 같은 화면이 출력...

위 화면의 html은

[signup.html]

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
<script type="text/javascript">
    //jQuery 문법
    $(document).ready(function(){    
        $('#box2').submit(function(e){
            e.preventDefault();
            //Ajax 문법
            $.ajax({
                type : 'POST',
                url : 'http://ip주소:80/php/join',
                data : $(this).serialize(),
                success : function(result){
                    if(result=="IDcheck"){
                        alert("입력하신 아이디가 이미 존재 합니다. 다른 아이디로 입력하세요.");
                    }else if(result=="Success save"){
                        alert("회원 가입을 축하합니다. 로그인을 해주세요.");
                        location.replace('http://192.168.0.2:80/php/login')
                    }else if(result=="Fail save"){
                        alert("회원 가입에 실패 했습니다. 다시 시도해 주세요.");
                    }else if(result=="Empty ID"){
                        alert("아이디를 입력하지 않았습니다. 아이디를 입력하세요.");
                    }else if(result=="Empty PWD"){
                        alert("비밀번호를 입력하지 않았습니다. 비밀번호를 입력하세요.");
                    }else if(result=="Empty NAME"){
                        alert("이름을 입력하지 않았습니다. 이름을 입력하세요.");
                    }else if(result=="Empty PHONE"){
                        alert("전화번호를 입력하지 않았습니다. 전화번호를 입력하세요.");
                    }
                },
                error : function(xtr,status,error){
                    alert(xtr +":"+status+":"+error);
                }
            });
        });
    });
    </script>
    <body>
        <div id = "box1">
            <form id = "box2" method="POST">
                <fieldset >
                <legend>입력 사항</legent>
                    <table>
                    <tr>
                        <td>아이디</td>
                        <td><input type ="text" name = "UID" placeholder="Enter Your Email"></td>
                    </tr>
                    <tr>
                        <td>비밀번호</td>
                        <td><input type ="text" name = "UPWD" placeholder="Enter Your Password"></td>
                    </tr>
                    <tr>
                        <td>이름</td>
                        <td><input type ="text" name = "UNAME" placeholder="Enter Your Name"></td>
                    </tr>
                    <tr>
                        <td>전화번호</td>
                        <td><input type ="text" name = "UPHONE" placeholder="Enter Your Phone"></td>
                    </tr>
                    </table>
                    <input type ="submit" value="가입하기">
                </fieldset>
            </form>
        </div>
    </body>
 
 

 

[join.php]

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
<?php
 
//signup.html form에서 POST로 보내온 회원 정보
$ID = $_POST['UID'];
$PWD = $_POST['UPWD'];
$NAME = $_POST['UNAME'];
$PHONE = $_POST['UPHONE'];
 
//MYSQL 접속 정보
$db = mysqli_connect("127.0.0.1:3306","DB사용자","DB비번","DB");
if(!$db){
    die("Error ".mysqli_connect_error());
}
 
//입력 항목 중 빈공간으로 입력 할 경우 체크
if($ID == NULL){
    echo "Empty ID";
}else if($PWD == NULL){
    echo "Empty PWD";
}else if($NAME == NULL){
    echo "Empty NAME";
}else if($PHONE == NULL){
    echo "Empty PHONE";
}else{
    //회원 가입하고자 하는 아이디가 이미 존재하는지 확인
    $compare_sql = "SELECT userID FROM member WHERE userID = '$ID'";
    $compare_result = $db->query($compare_sql);
 
    //DB에서 가져온 결과값이 1개 이상이고, 그 결과값이 입력한 ID와 같다면 DB에 존재하므로 다른 아이디로 시도...매세지 출력
    if($compare_result->num_rows == 1){
 
        //DB에서 가져온 결과값을 행렬로 변환 하여 DATA 접근
        $row=$compare_result->fetch_array(MYSQLI_ASSOC);
        if($row['userID']==$ID){
            echo "IDcheck";
        }
    }else{  //DB에 입력한 아이디와 동일한 아이디가 없다면 DB에 저장
        $sql = "INSERT INTO member (userID, userPWD ,userNAME, userPHONE) VALUES ('$ID','$PWD','$NAME','$PHONE')";
        $result = $db->query($sql);
 
        //저장 되었다면 성공, 아님 실패
        if($result){
            echo "Success save";
        }else{
            echo "Fail save";
        }
    }
}
 
mysqli_close($db);
?>
 

 

WAMP 란?

Windows Apache Mysql Php 의 약자이며, mysql과 php를 내장한 윈도우에서 돌아가는 웹 서버이다.

 

wamp를 이용하여 login 기능을 한번 짜보자.

들어가기에 앞서 session의 개념을 알지 못한다면 그것부터 공부 하는것이 순서입니다.

 

아~ 그리고 필자는 비동기 방식으로 하고 싶어서 Ajax를 한번 이용해 보겠습니다.

 

우선 mysql

[mysql]

 

[login.html]

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
<!DOCTYPE html>
<html>
    <meta charset="utf-8" />
    <!-- jQuery 사용 명시 -->
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <head>
        <title>로그인 페이지</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="login.css">
 
        <!-- 구글 웹 폰트 -->
        <link href="https://fonts.googleapis.com/css?family=Nanum+Brush+Script" rel="stylesheet">
        <style>
            body
            {
                font-family: 'Nanum Brush Script', cursive;
            }
        </style>
    </head>
    <script type="text/javascript">
    $(document).ready(function(){
        $('#form_data').submit(function(e){
            e.preventDefault();
            $.ajax({
                type : 'POST',
                url : 'http://IP주소:80/php/login_check',
                data : $(this).serialize(),
                success : function(result){
                    if(result=="success"){
                        alert("로그인 성공");
                        location.replace('http://IP주소:80/php/main')
                    }else if(result=="Fail:session"){
                        alert("세션 저장 실패...다시 시도 해주세요.");
                    }else if(result=="Fail:password"){
                        alert("비밀번호가 틀렸습니다. 다시 시도 해주세요.");
                    }else if(result=="Fail:empty"){
                        alert("회원 정보가 없습니다. 회원가입을 해주세요.");
                    }
                },
                error : function(xtr,status,error){
                    alert(xtr +":"+status+":"+error);
                }
            });
        });
    });
    </script>
    <body>
        <div id="loginer">
            <div id="form">
                <form id="form_data" method ="POST">
                    <fieldset>
                    <legend>LOGIN !</legend>
                    <input type="text" name="UID" id="UID" placeholder="Enter Your Email">
                    <br><br>
                    <input type="password" name="UPWD" id="UPWD" placeholder="Enter Your Password">
                    <br><br>
                    <input type="submit" value="login!" id="login_button">
                    <br><br>
                    You Don't Have Your Account?<a href="signup.html">
                    </fieldset>
                </form>
            </div>
        </div>
    </body>
</html>
 

 

[login.css]

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
#loginer
{
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #bcbcbc;
  text-align: center;
}
#form
{
  font-size: 1.3em;
  width: 50%;
  display: inline-block;
}
::placeholder
{
  font-size: 1.3em;
  font-family: 'Nanum Brush Script', cursive;
}
button
{
  border: 0px;
  background-color: white;
}
#signupimg
{
  font-size: 1em !important;
}
 
 

 

[login_check.php]

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
<?php
//session에 저장된 data 가져오기
session_start();
 
//login.html에서 post방식으로 전달한 아이디,비번 받기 
$ID=$_POST['UID'];
$PWD=$_POST['UPWD'];
 
//phpmyadmin db에 접속
$db = mysqli_connect("127.0.0.1:3306","DB사용자","DB비번","DB명");
if(!$db){ //db에 접속이 안되면 에러 알림... 
    die("Error ".mysqli_connect_error());
}
 
#db에 접속 성공시--------------------------------------------------------------
//Query문
$sql = "SELECT userID,userPWD FROM member where userID = '$ID'";
 
//Query문 결과 result변수에 저장
$result = $db->query($sql);
 
//Query문 결과로 가져온 값이 한 줄이라도 있다면 true, 아니면 false
if($result->num_rows==1){
 
    //가져온 data를 행열로 바꾸어줌, table의 컬럼명으로 data에 접근하는것을 쉽게 하기위해서...
    $row=$result->fetch_array(MYSQLI_ASSOC);
    
    //login.html에서 입력한 비번과 db에 들어있는 비번이 같은지 비교
    if($row['userPWD']==$PWD){
        
        //같다면 아이디를 session에 저장
        $_SESSION['userID']=$ID;
        
        //성공적으로 저장 했다면 main으로 이동, 저장 실패면 login화면으로 다시 이동
        if(isset($_SESSION['userID'])){
            //성공
            echo "success";
        }else{
            //실패 : session저장 실패
            echo "Fail:session";
        }
    }else{
        //실패 : 비번이 같지 않음
        echo "Fail:password";
    }
}else{
    //실패 : db에 아이디 존재하지 않음
    echo "Fail:empty";
}
mysqli_close($db);
?>
 

 

[logout.php]

1
2
3
4
5
6
7
<?php
session_start();
$res=session_destroy();
if($res){
    header('Location: http://IP주소:80/php/login');
}
?>
 

 

[main.php]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<meta charset ="utf-8"/>
<?php
session_start();    //session 가져오기
 
//session에 데이터가 없다면 로그인 화면으로 GO
if (!isset($_SESSION['userID'])) {
    header('Location : http://IP주소:80/php/login');
}
 
echo "<h1>로그인 성공</h1><br>";
echo "<a href=logout.php>로그아웃</a>"
 
?>
 
 

 

다음에는 회원가입하는 코드를 짜보도록 하겠습니다.

+ Recent posts