728x90

목차

  1. main 페이지
  2. Read 기능
  3. Create 기능
  4. Update 기능
  5. Delete 기능

 

CRUD_Board_1.zip
0.00MB

 


1. main

[목차로 이동]

CRUD_mian.php

* 저장된 파일들의 이름이 CRUD_main.php 에 알파벳 순서대로 출력되고, 파일을 생성/수정한 최종 날짜가 같이 출력된다.
* scandir('dir')은 디렉토리에 있는 파일목록을 배열의 형태로 반환해주며 첫번째, 두번째 배열에는 '.'과 '..'이 있기 때문에 if문으로 처리해준다. 

* for문을 이용해 <?=$list[$i]>을 순차적으로 출력하고 이를 제목으로 사용한다. 또 <a>에 title 파라미터를 전달받은 read.php주소를 담는다.
* 파일의 최종 수정 날짜를 date포맷으로 출력하기 위해서는 filemtime('dir') 사용한다. 또, 출력된 날짜가 한국시간이 아닐 수 있는 데 이런 경우는 date_default_timezone_set("Asia/Seoul");를 코딩한다.

** echo "파일을 찾을 수 없습니다."; - 오타수정

//CRUD_main.php

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      .main {
        border : 1px solid;
        width : 450px;
        height : 300px;
        margin : 0px auto;
        overflow : scroll;
      }
    </style>
  </head>
  <body>
    <div class="main">
      <div align="center">
        <table border="1" style="border-collapse : collapse;">
          <tr>
            <th style="background-color: #d8d8d8; width : 200px;">파일이름</th>
            <th style="background-color: #d8d8d8; width : 220px;">수정날짜</th>
          </tr>
            <?php
              $list = scandir('./textSample');
              for ($i=0; $i < count($list); $i++) {
                if($list[$i] !='.' ){
                  if($list[$i] !='..'){?>
                    <tr>
                      <td name="title">
                      <?=$i-1?>. <a style="text-decoration : none; color : black;"
                       href=./CRUD/read.php?title=<?=$list[$i]?> ><?=$list[$i]?></a>
                      </td>
                      <td style="text-align : center;">
                        <?php
                          date_default_timezone_set("Asia/Seoul");
                          $filename = './textSample/'.$list[$i];
                          if (file_exists($filename)) {
                            echo date("y/n/d A h:i", filemtime($filename));
                          }else {
                            echo "파일을 찾을 수 없습니다.";
                          }//else?>
                      </td>
                    </tr>
              <?php }//if_2
                  }//if_1
                }//for
              ?>
        </table>
      </div>
    </div>
    <p style="text-align:center;">
      <input type="button" name="new" value="파일생성" onclick="location.href='./CRUD/create.php'">
    </p>
  </body>
</html>

2. Read

[목차로 이동]

* 파일생성을 누르면 글쓰기 페이지로 이동하고 '저장'을 누르면 제목과 내용이 저장된다. (단, 제목에 공백이 있다면 파일은 생성되지만 읽어올 때 에러가 발생한다)
* CRUD_main.php에서 title로 전달 받은 파라미터로 '제목'을 채우고 file_get_contents( ); 에 경로를 받은 파라미터로 경로를 채워 내용을 읽어온다.

//read.php

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      .main3{
        border : 1px solid;
        margin: 0px auto;
        width: 400px;
        height: 400px;
        text-align: center;
      }
    </style>
    <script type="text/javascript">
    function del( f ) {
      if (confirm("해당 게시글을 삭제하시겠습니까?")) {
        f.action = "../process/delete_process.php";
        f.method = "post";
        f.submit();
      } else {
        return;
      }
    }
    </script>
  </head>
  <body>
      <h3 style="text-align : center;">::: 게시글 :::</h3>
      <table border="1" style="border-collapse : collapse; margin : 0px auto;">
          <tr>
            <th style="background-color: #d8d8d8;">제목</th>
            <td name="read_title" style=" text-align : center;"><?=$_GET['title']?></td>
          </tr>
          <tr>
            <th style="background-color: #d8d8d8;">내용</th>
            <td name="read_contents" style="width : 200px; height : 200px; padding : 10px;">
            	<?=file_get_contents('../textSample/'.$_GET['title'])?>
            </td>
          </tr>
          <tr style="text-align : center;">
              <td colspan="2">
                <form class="" action="./update.php" method="post" style="display : inline;">
                  <input type="hidden" name="update" value="<?=$_GET['title']?>">
                  <input type="submit" name="" value="수정">
                </form>
                <form style="display : inline;">
                  <input type="hidden" name="title" value="<?=$_GET['title']?>">
                  <input type="button" value="삭제" onclick="del(this.form);">
                </form>
                <input type="button" value ="돌아가기"
                onclick="location.href='../CRUD_main.php'">
              </td>
          </tr>
      </table>
  </body>
</html>

3. Create

[목차로 이동]

 

create.php
create_process.php

* '파일생성'을 누르면 create.php로 이동하고 제목과 내용을 입력한 후 '저장'을 누르면 파라미터로 create_process.php로 전달된 후 처리된다. 이후 제목과 내용에 해당되는 파일이 생성됨 
* form태그에 파라미터 전달 경로(action)와 전송 방법(method)를 코딩한 후 저장버튼(submit)을 만들어 준다. 저장버튼을 누르면 text와 textarea에 있는 value값이 각 각 tilte과 description 파라미터에 담겨 전달된다.  
* create.php에서 제목(title)과 내용(description)이 post형식으로 전달되면 file_put_contents();로 제목에 해당되는 파일을 만들고 그 파일에 내용을 넣는다.
* 파일이 정상적으로 생성돼 있는지 for문을 사용해 확인하고 정상적으로 생성됐다면 header('Location: ');에 지정된 경로로 이동한다.

//create.php

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      .main2{
        width: 400px;
        height: 200px;
        margin: 0px auto;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div class="main2">
    <form action="../process/create_process.php" method="post">
      <h3>::: 글쓰기 :::</h3>
      <table border="1" style="margin : 0px auto;">
        <tr>
          <th style="background-color: #d8d8d8;">제목</th>
          <td><input type="text" name="title"></td>
        </tr>
        <tr>
          <th style="background-color: #d8d8d8;">내용</th>
          <td><textarea type="textarea" name="description" rows="10" cols="20"></textarea></td>
        </tr>
        <tr>
          <td colspan="2" style="text-align:center;">
            <input type="submit" name="" value="저장">
            <input type="button" value ="돌아가기" onclick="location.href='../CRUD_main.php'">
          </td>
        </tr>
      </table>
    </form>
    </div>
  </body>
</html>
//create_process.php
<?php
  file_put_contents('../textSample/'.$_POST['title'], $_POST['description']);
  $list = scandir('../textSample');
  for ($i=0; $i < count($list) ; $i++) {
    if ($list[$i]==$_POST['title']) {
      header('Location: ../CRUD_main.php');
    }//if
  }//for
?>

4. Udate

[목차로 이동]

read.php
update.php
update_process.php

* read.php에서 '수정'을 누르면 update.php로 숨겨진(hidden) 태그에 담겨진 value값을 update 파라미터에 담아서 전달한다. 
* 기존 제목을 old_title로 이름을 input 태그에 담고 숨긴다.(update_process.php에서 old_title로 기존 파일을 찾아서 new_title로 바꿔주기 위해서 숨겨 놓음)
* '완료' 버튼을 누르면 form 태그에 있는 value값들이 old_title, new_title, description 담겨 파라미터로 update_process.php 로 전달된다.
* update_process.php에서 파라미터를 받으면 rename( );은 old_title 파라미터에 담긴 value에 해당하는 파일이름을 new_title 파라미터에 담긴 value 값으로 바꿔준다.
* 제목과 이름이 수정된다면 수정이 완료된 read.php로 이동한다.

//update.php

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <form class="" action="../process/update_process.php" method="post">
      <h3 style="text-align : center;">::: 글 수정 :::</h3>
      <table border="1" style="margin : 0px auto;" >
        <input type="hidden" name="old_title" value="<?=$_POST['update'] ?>">
        <tr>
          <th style="background-color: #d8d8d8; ">제목</th>
          <td><input type="text" name="new_title" style="width : 200px;"
          value="<?=$_POST['update'] ?>"></td>
        </tr>
        <tr>
          <th style="background-color: #d8d8d8;">내용</th>
          <td><input type="text" name="description" style="width : 200px; height : 200px;"
          value="<?=file_get_contents('../textSample/'.$_POST['update'])?>"></td>
        </tr>
        <tr>
          <td colspan="2" style="text-align:center;">
            <input type="submit" value="완료">
            <input type="button" value ="돌아가기"
            onclick="location.href='../CRUD_main.php'">
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>
//update_process.php
<?php
  rename('../textSample/'.$_POST['old_title'], '../textSample/'.$_POST['new_title']);
  file_put_contents('../textSample/'.$_POST['new_title'], $_POST['description']);
  header('Location: ../CRUD/read.php?title='.$_POST['new_title']);
?>

 


5. Delete

[목차로 이동]

read.php
read.php
delete_process.php

* '삭제버튼'을 누르면 form태그 안 value들이 같은 태그 안 name에 담겨 자바스크립함수 del( );로 전달된다.
* 브라우저 창에 confirm창을 띄우고 yes를 누르면 True영역인 if안의 문장을 실행하고 delete_process.php로 title 파라미터에 value가 담겨 전달된다. 
* delete_process가 파라미터를 전달받아 파일경로를 만들면 unlink( );를 통해서 해당파일을 삭제하고 header('Location : ')안에 있는 페이지로 이동하며 삭제가 끝난다.(if문으로 파일삭제가 성공했을 때와 아니었을 때를 구현했으면 조금 더 나았을 텐데 아쉬움이 남는 부분)

//delete_process.php

<?php
  unlink('../textSample/'.$_POST['title']);
  header('Location: ../CRUD_main.php');
?>

 

728x90

+ Recent posts