웹개발(PHP-Mysql)

[웹 개발] CRUD(생성,읽기,수정,삭제) 페이지 만들기

무너박사 2024. 7. 15. 13:29

저번시간엔 로그인&로그아웃 인증을 구현하였습니다.

 

https://jamesbexter.tistory.com/entry/2%EC%A3%BC%EC%B0%A8-%EA%B3%BC%EC%A0%9C-%ED%9A%8C%EC%9B%90%EA%B0%80%EC%9E%85-%ED%8E%98%EC%9D%B4%EC%A7%80-%EB%A7%8C%EB%93%A4%EA%B8%B0

 

<2주차 과제> 회원가입 페이지 만들기

:  DB를 연동한 회원가입 및 로그인 페이지를 만들어라!           페이지 소개코드 분석1.    드디어 전과 다르게 Sign up 이라는 항목이 생겻다!이것을 누르게 되면! 이러한 회원가입 페이지

jamesbexter.tistory.com


 

이번시간은 게시글을 읽고 쓰고 수정 삭제 할수있는 페이지를 만들어보았습니다.

 

    <목차>

1. C(create) - "post_write.php"

2. R(read) - "post_read.php"

3. U(update) - "post_update.php"

4. D(delete) - "post_delete.php"

 

 


< C(create) >

첫번째는 글쓰기 페이지 입니다.

 

메인페이지에서 게시글 작성을 클릭

 


 

post_write.php 에서 글을 쓴후 작성을 누르면 post_upate_prc.php 로 이동하여 글을 작성하는 코드가 실행됩니다.

post_write.php

 


게시글 작성완료 메시지

코드설명

 

<post_write.php>

<?php 
    session_start(); 
    if(!($_SESSION['loggedin'])){	// 점프해서 mypage.php 로 오는것을 방지.
        header('Location: /index.php');
        exit();}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="div.css" rel="stylesheet" type = "text/css">
    <title>Posting</title>

    <style>     /*a 태그 스타일시트*/
        a:link {
            color : black;
            text-decoration-line: none;
        }
        a:hover{
            text-decoration-line: underline;
        }
        textarea{
            font-size:1.5em;
        }
    </style>
</head>

<body>
    <div style="text-align:center" class="yellowfull">
        <div style="position:absolute;font-weight:bold; right:60px; top: 45px;">
                <a href="page.php">BACK</a>
        </div>

        <form action="post_write_prc.php" method="POST">
        <input type="text" name="post_name" placeholder="제목" maxlength='20' style="text-align:center;position:absolute;background-color:white; width:60%; height:10%;transform:translate(35%,100%);font-size:20px" class="login-box">
        <textarea type="text" name="contents" placeholder="내용" maxlength='750' style="text-align:center;position:absolute;background-color:white; width:60%; height:65%;transform:translate(35%,35%)" class="login-box"></textarea>
        <div style="position:absolute;bottom:20px;right:38.2%;width:20%;">
        <input style="height:30px;background-color:#dcdcdc" type = submit class="submit-btn" value="작성"></div>
    </div>


</body>
</html>

 

<post_write_prc.php>

<?php 
    include 'dbcon.php';

    session_start(); 
    if(!($_SESSION['loggedin'])){	// 점프해서 mypage.php 로 오는것을 방지.
        header('Location: /index.php');
        exit();}
    
    $post_name=$_POST['post_name'];
    $contents=$_POST['contents'];
    $post_writer=$_SESSION['username'];

    if($post_name==NULL||$contents==NULL){
        echo "<script>alert('작성하지 않은 내용이 있습니다!');  
        window.location.href='/'
        </script>";
    }else{
        $sql = "insert into postinfo (post_name,contents,postwriter) values ('".$post_name."','".$contents."','".$post_writer."')";
         $result = mysqli_query($dbcon,$sql);

        echo "<script>alert('게시글이 작성되었습니다!!');  
        location.href='/index.php'
        </script>";  
        exit();
    }
?>

 


< R(read) >

 

게시글 목록에서 게시글을 열람하여 post_read.php 로 접근해줍니다.

 


 

게시글 읽기 게시판은 이렇게 구성하였습니다.

아래쪽 수정과 삭제 버튼을 두어 동작할 수 있게 하였으며 우측 상단에 뒤로가기 버튼을 추가하였습니다.


코드설명

 

<post_read.php>

<?php 
    include 'dbcon.php';

    session_start(); 
    if(!($_SESSION['loggedin'])){	// 점프해서 mypage.php 로 오는것을 방지.
        header('Location: /index.php');
        exit();}

    $idx=$_GET['idx'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="div.css" rel="stylesheet" type = "text/css">
    <title>Posting</title>

    <style>     /*a 태그 스타일시트*/
        a:link {
            color : black;
            text-decoration-line: none;
        }
        a:hover{
            text-decoration-line: underline;
        }
    </style>
</head>

<body>
    <div style="text-align:center" class="yellowfull">
        <div style="position:absolute;font-weight:bold; right:60px; top: 45px;">
                <a href="page.php">BACK</a>
        </div>

        <?php
            $sql = "select * from postinfo where idx='".$idx."'";
            $result = mysqli_query($dbcon,$sql);
            $row=mysqli_fetch_array($result);
        ?>

        <div style="position:absolute;background-color:white; width:60%; height:10%;transform:translate(35%,100%)" class="login-box">
            <div style="text-align:center;">
                <?php echo $row['post_name']; ?>
            </div>
        </div>
        <div style="position:absolute;background-color:white; width:60%; height:65%;transform:translate(35%,35%)" class="login-box">
                <?php echo $row['contents']; ?>
        </div>

        <form action="post_delete.php" method="POST">
        <input type="hidden" name="idx" value="<?php echo $idx ?>">
        <div style="position:absolute;bottom:20px;right:28%;width:20%;">
        <input style="height:30px;background-color:#dcdcdc" type = submit class="submit-btn" value="삭제"></div></form>

        <form action="post_update.php" method="GET">
        <input type="hidden" name="idx" value="<?php echo $idx ?>">
        <div style="position:absolute;bottom:20px;left:30%;width:20%;">
        <input style="height:30px;background-color:#dcdcdc" type = submit class="submit-btn" value="수정"></div></form>
    </div>


</body>
</html>

 

 


< U(update) >

게시글 수정 누르기(post_read.php)

 


 

게시글 수정을 완료하면 post_update_prc.php 로 이동하여 수정코드를 진행해주었습니다.

※수정하는것은글쓴이 외에는 하면 안되기때문에 인증절차를 추가해주었습니다.

게시글 수정 페이지(post_update.php)

 


코드설명

 

<post_update.php>

<?php 
    include 'dbcon.php';

    session_start(); 
    if(!($_SESSION['loggedin'])){	// 점프해서 mypage.php 로 오는것을 방지.
        header('Location: /index.php');
        exit();}

        $idx=$_GET['idx'];                                 // DB에서 update 를 위한 인증정보 가져오기
        $sql = "select * from postinfo where idx=".$idx;
        $result = mysqli_query($dbcon,$sql);
        $row=mysqli_fetch_array($result);

        $post_writer=$row['postwriter'];//변수설정
        $post_name=$row['post_name'];
        $contents=$row['contents'];

        if($post_writer!=$_SESSION['username']){        //수정을 하기전 update를 위한 인증절차,통과 x 시 index.php 로 리다이렉션.
            echo "<script>alert('권한이 없습니다.');
             location.href='/index.php'
            </script>";  
        exit();
        }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="div.css" rel="stylesheet" type = "text/css">
    <title>Posting</title>

    <style>     /*a 태그 스타일시트*/
        a:link {
            color : black;
            text-decoration-line: none;
        }
        a:hover{
            text-decoration-line: underline;
        }
        textarea{
            font-size:1.5em;
        }
    </style>
</head>

<body>
    <div style="text-align:center" class="yellowfull">
        <div style="position:absolute;font-weight:bold; right:60px; top: 45px;">
                <a href="page.php">BACK</a>
        </div>

        <form action="post_update_prc.php" method="POST">
        <input type="hidden" name="idx" value=<?php echo $idx; ?>>
        <input type="text" name="post_name" placeholder="제목" maxlength='20' value="<?php echo $post_name; ?>" style="text-align:center;position:absolute;background-color:white; width:60%; height:10%;transform:translate(35%,100%);font-size:20px" class="login-box">
        <textarea type="text" name="contents" placeholder="내용" maxlength='750' style="text-align:center;position:absolute;background-color:white; width:60%; height:65%;transform:translate(35%,35%)" class="login-box">
        <?php echo $contents; // 내용에 들어갈 contents 삽입 ?>   
        </textarea>
        <div style="position:absolute;bottom:20px;right:38.2%;width:20%;">
        <input style="height:30px;background-color:#dcdcdc" type = submit class="submit-btn" value="완료"></div>


    </div>


</body>
</html>

 


 

<post_update_prc.php>

<?php 
    include 'dbcon.php';

    session_start(); 
    if(!($_SESSION['loggedin'])){	// 점프해서 page.php 로 오는것을 방지.
        header('Location: /index.php');
        exit();
    }

    $idx=$_POST['idx'];              // DB에서 update 를 위한 인증정보 가져오기
    $sql = "select * from postinfo where idx=".$idx;
    $result = mysqli_query($dbcon,$sql);
    $row=mysqli_fetch_array($result);

    $post_writer=$row['postwriter']; // 수정할 정보 변수설정   
    $post_name=$_POST['post_name'];
    $contents=$_POST['contents'];

    if($post_writer==$_SESSION['username']){            //글작성자와 세션의 사용자가 같은지 인증
        $sql = "update postinfo set post_name='".$post_name."',contents='".$contents."' where idx=".$idx;
        $result = mysqli_query($dbcon,$sql);

            //인증 완료시 게시글 삭제
        echo "<script>alert('게시글이 수정되었습니다!!'); 
            location.href='/index.php'
            </script>";  
            exit();
    }else{  //인증 X 일때 권한이 없다한 후 index.php 로 리다이렉션
        echo "<script>alert('잘못된 접근입니다.');
        location.href='/index.php'
        </script>";  
        exit();
    }

?>

 


 

< D(delete) >

읽기 페이지에서 삭제 누르기(post_read.php)

 


글쓴이가 맞는지 확인후(인증철차) post_delete.php 에서 삭제절차 시작

 


코드설명

 

<post_delete.php>

<?php 
    include 'dbcon.php';

    session_start(); 
    if(!($_SESSION['loggedin'])){	// 점프해서 page.php 로 오는것을 방지.
        header('Location: /index.php');
        exit();
    }

    $idx=$_POST['idx'];                                 // DB에서 delete 를 위한 인증정보 가져오기
    $sql = "select * from postinfo where idx=".$idx;
    $result = mysqli_query($dbcon,$sql);
    $row=mysqli_fetch_array($result);
    $post_writer=$row['postwriter'];

    if($post_writer==$_SESSION['username']){            //글작성자와 세션의 사용자가 같은지 인증
        $sql = "delete from postinfo where idx=".$idx;
        $result = mysqli_query($dbcon,$sql);

            //인증 완료시 게시글 삭제
        echo "<script>alert('게시글이 삭제되었습니다!!'); 
            location.href='/index.php'
            </script>";  
            exit();
    }else{  //인증 X 일때 권한이 없다한 후 index.php 로 리다이렉션
        echo "<script>alert('권한이 없습니다.');
        location.href='/index.php'
        </script>";  
        exit();
    }

?>

 

 


 

긴 글 읽어주셔서 감사합니다!