Mysql/php 게시판 만들기

2019. 7. 3. 23:58

원래 낮에 포스팅을 해야하는데 끝이 없는 삽질로 인해 오늘 포스팅이 조금 늦었다. 바로 정리해보겠다.

아침부터 삽질하던 한글화 문제는 단순히 오타로 인한 것이였지만 그래도 덕분에 많은걸 볼 수 있었다.

 

우선 어제 만졌던 Login페이지의 코드와 화면을 보겠다.

 

[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
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html>
        <head>
                <title>DOHEE'S LOGIN PAGE"</title>
        
<style>
 
#login{
        text-align:center;
}
.button {
        width:50px;
        background-color:#f8585b;
        border:none;
        color:#fff;
        padding:10px 0;
        text-align: center;
        text-decoration: none;
        display:inline-block;
        font-size: 15px;
        margin:  3px;
        border-radius:10px;
        cursor: pointer;
        }
 
.box1{  
        width:300px;
        height:290px;
        margin:auto;
        text-align:center;
}
</style>
 
 
        </head>
        <body>
        <div id="login">
                <strong>
                        <h2>LOGIN</h2>
                </strong>
                <br>
 
        <table style="margin-left:auto; margin-right:auto;">
                <tr align="center">
 
                <form action= "data.php" method="post">
                        <td>    ID :</td>
                        <td>    <input type="text" name="username"><br></td>
                </tr>
                <tr align="center">
                        <td>    Password:</td>
                        <td><input type="password" name="password"><br></td>
                </tr>
        </table>
                        <br>
 
                         <input type="submit" value="LOGIN">
                         <br>
                         <br>
                        <!--     <div class="button">-->
                         <!--   </div>-->
                </form>
 
                <div class="box1">
                        <div style="border:2px solid; padding:10px; line-height:10%;">
                         <a href="Join.html">JOIN</a>
                         <h5>아직 회원이 아니시면</h5>
                         <h5>Join us!</h5>
                        </div>
                </div>
 
              </div>
        </body>
 
 
 
</html>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

Login page에 어제와 달리 기능을 조금 더 추가했다. pw와 id창에 아무것도 치지 않았을 경우에는 자바스크립트를 이용하여 알림창을 내보내고 다시 세션을 이용해 이전의 페이지를 보여주는 코드를 추가했다.

 

이제 오늘 만든 메인은 바로 로그인 페이지 이동 후 나오는 게시판이다. 게시판에서 많이 삽질을 했다..

한글화에 힘을 쓰면서 얻은 mysql 명령어를 쭉 정리하고자한다.

 

우선 게시판의 결과화면과 메인코드이다.

[show_board.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
<?php   
        include './db_info.php';
        $query = "select * from new_board"; #게시판 정보 불러오기
        $result = mysqli_query($conn,$query);
 
?>
 
<h2>Board</h2>
<h5>자유게시판입니다. 자유롭게 글을 써주세요.</h5>
<table width = "800" border="1" cellspacing="0" cellpadding="5">
<tr align="center">
<td bgcolor="#cccccc">번호</td>
<td bgcolor="#cccccc">제목</td>
<td bgcolor="#cccccc">작성자</td>
</tr>
 
 
<?php
 
           while($row=mysqli_fetch_array($result)) {
 
                   echo "<tr>";
                   echo "<td>".$row['no']."</td>";
                   echo "<td>".$row['title']."</td>";
                   echo "<td>".$row['name']."</td>";
                   echo "</tr>";
 
           }
?>
 
</table>
<br>
<br>
<button type="button" onclick="location.href='write.html'">글쓰기</button><br>
<br>
<button>로그아웃</button>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

[data.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
<?php
  
header('Content-Type: text/html; charset=utf-8');
        include './db_info.php';
        $query = "select * from Login";
        $result = mysqli_query($conn,$query);
 
        while($row=mysqli_fetch_array($result)){
 
        $str=strcmp($row["id"],$_POST['username']);#문자열 비교
        $pwstr=strcmp($row["pw"],$_POST['password']);
        $key1;
 
        if(!$str&&!$pwstr){
        #       echo $row["id"]."님 로그인 되셨습/니다.<br>";
                echo ("<script>alert('로그인 되셨습니다.')</script>");
        #자바스크립트 다음에 게시판 페이지가 나오게 하고 싶은데
        #안된다... 이부분 나중에 해결하기
        #       echo ("<script>location.href(./show_board.php);</script>");
                header("Location:./show_board.php");
                break;
        }
        else if(empty($_POST['username']) || empty($_POST['password'])){ #아무 값도 입력되지 않았을 경우
                echo ("<script>alert('비밀번호와 ID 모두를 입력해주세요')</script>");
                $key0;
                break;
        }else {
                $key = 1;
                }
        }
 
        if($key==1 &&($str || $pwstr)){
                echo "로그인실패";
        }else if($key==0){ #세션 종료 시 동작 구현      
                echo "<meta http-equiv='refresh' content='0;url=Login.html'>";
                }
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

위의 코드 data.php를 보면 show_board.php를 로그인 결과가 맞으면 이동하는 형식으로 구현했다.

php에서 php간의 연결 방법은 여러가지가 있지만 나는 header가 명확하게 느껴졌기 때문에 저 코드를 사용했다.

 

<php간의 문서 이동 코드>

1. 자바스크립트

echo ("<script>location.href('경로/파일이름');</script>");

2. header 이용

header("Location:'경로/파일이름'");

 

계속해서 Board 페이지에 글쓰기 버튼을 누르면 아래와 같은 화면을 볼 수 있다. 게시판의 글쓰기 페이지이다. 

오늘은 데이터베이스에 연결하여 정보를 푸쉬하는 것까지만 구현하였다. 이 post로 보내는 과정에서 정보가 깨져서 내일은 이 부분에 대한 한글화 문제를 해결할 예정이다. 이 점을 감안하고 봐주길 바란다.

 

[Write.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
<?doctype html>
<html>
        <head>
                <title>Wirte Down!</title>
                <meta charset="utf-8"/>
                <!--    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>-->
<style>
.texts{
        text-align:center;
        line-height:20%;
}
</style>
        </head>
 
        <body>
 
                <div class=texts>
                        <form action="load_write.php" method="POST">
                        <br><strong><h2>Write</h2><strong><br>
                        <h5>제목:</h5>
                        <input type="text" name="textbox"
                        style="width:270px; height:30px; word-break:normal;"><br>
                        <h5>작성자:</h5>
                        <input type="text" name="id"
                         style="width:270px; height:30px; word-break:normal;"><br>
                        <h5>내용:</h5>
                        <!--    <textarea rows="20" cols="40"></textarea><br>-->                
                        <input type="text" name="write"
                        style="width:270px; height:100px; word-break:normal;"><br>
                        <br>
                        <br>
                        <input type="submit" value="글쓰기">
                        <button type="button" onclick="location.href='show_board.php'">돌아가기</button><br>
                      </form>
                </div>
        </body>
 
</html>
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

게시글을 쓸 때 정보를 위한 기본적인 틀만 마련했다. 이 부분의 정보는 데이터베이스에 고스란히 옮겨져야 하므로 제목(title), 내용(content), 작성자(name)으로 나눴다.

 

이 정보를 전달하기 위한 php코드를 작성하였다. 그 코드는 아래와 같다.

 

[load_write.php]

1
2
3
4
5
6
7
8
9
10
11
12
<?php
  
        header("Content-type:text/html;charset=utf-8");
        include './db_info.php';
        $conn=mysqli_connect("localhost","ire4564","qwer","ire4564");
        $title=$_POST['textbox'];
        $content=$_POST['write'];
        $name=$_POST['id'];
        $result = mysqli_query($conn"insert into new_board (title,content,name) values ('$title','$content','$name')");
        $result = mysqli_query($conn,$query);
?>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
h

우선 쿼리문을 쿼리 변수에 넣어 insert 명령어를 실행시킨 다음 실행시킨 결과에 따라 데이터베이스에 각각의 폼에서 받은 정보들을 알맞은 테이블로 전송시켜주었다. 하지만 이 과정에서 앞서 언급했다싶히 한글화 문제가 발생했으므로 내일의 과제는 이것을 해결하는 것이 목표이다.

 

여기까지가 만든 페이지에 대한 결과 코드이고, 마지막으로 mysql에 대한 명령어를 기록용으로 남겨두고 글을 마치려고 한다. 오늘 많이 써본 다양한 명령어들은 아래와 같다. 참고 그림 사진과 함께 첨부하겠다.

 

<mysql 명령어 정리>

1. Default 값 변경

각 테이블의 필드의 default값을 변경해야 할 상황이 왔다. 그래서 num필드의 default값을 바꾸기 위해 아래와 같은 명령어를 사용하였다.

alter table '테이블명' modify '필드명' '자료형' default '변경할 값';

 

 

2. 테이블의 NULL 값만 찾아서 변경

테이블의 default값을 1로 변경 지정해주었으나 기존 값들은 바뀌지 않는다. 그렇지 때문에 명령어

update '테이블명' set '필드명'='지정값' 을 사용하였다.

 

3. 테이블의 자료형을 보여주기

show variables like "char%"; 

show create table '데이터베이스명'.'테이블명';

이 부분에서 잘못 설정되어있으면 한글화 과정에서 오류가 날수도 있다고 한다.

 

4. 기존 테이블에 새로운 필드 추가하기

alter table '테이블명' add '필드명' '자료형'

이렇게 하면 이미 만들어진 테이블에 필드를 추가하여 새로운 항목의 자료를 삽입할 수 있게된다.

BELATED ARTICLES

more