티스토리 뷰

지난 편에 이어 수정과 삭제하는 기능을 구현해보겠습니다. 중요한 것은 각 게시물의 primary key를 잘 가져오는 것과 session을 이용한 권한을 주는 것입니다.

전체 코드는 깃허브 https://github.com/dhffll/php-Mysql-Board에서 확인하실 수 있습니다.

 

저번까지 index.php 파일에서 제목 클릭 시 해당 게시물로 이동하는 코드를 짜두었습니다.

<tr>
    <td><?= $filtered['date'] ?></td>
    <td><a href="list.php?num=<?= $filtered['num'] ?>"><?= $filtered['title'] ?></a></td>
    <td><?= $filtered['writer'] ?></td>
</tr>

 

list.php

<?php 
    session_start();
    include 'mysql.php'; //$con

    //게시글을 보여주기 위한 쿼리
    $filtered_num = mysqli_real_escape_string($con, $_GET['num']);

    $sql = "select * from board left join member on board.writer = member.id where num = $filtered_num";

    $result = mysqli_query($con,$sql);

    $row = mysqli_fetch_array($result);

    $filtered = [
        'date' => htmlspecialchars($row['date']),
        'title' => htmlspecialchars($row['title']),
        'content' => htmlspecialchars($row['content']),
        'writer' => htmlspecialchars($row['id'])
    ];

    include 'header.php';
?>

<link rel="stylesheet" href="css/list.css">

    <p>date : <?=$filtered['date']?></p>
    <p>writer : <?=$filtered['writer']?></p>
    <p>title : <?=$filtered['title']?></p>
    <p>content : <?=$filtered['content']?></p>

    <?php 
        if($_SESSION['id'] == $filtered['writer']){ //작성자 권한
    ?> 
        <a href="update.php?num=<?=$filtered_num?>">update</a>
        <form style="display: inline-block;" action="delete.php" method="POST" id="form" onsubmit="return confirm('정말 삭제하시겠습니까?')">
            <input type="hidden" name="num" value="<?=$filtered_num?>">
            <input type="submit" value="delete">
        </form>
        <br><br>
    <?php       
        }
    ?>
    
    <p><a href="index.php">main</a></p>
    
<?php 
    include 'footer.php';
?>

작성자도 아닌데 아무나 글을 수정하거나 삭제하면 안되겠죠?

그래서 작성자의 아이디와 세션에 저장된 아이디가 동일할 시에만 수정, 삭제 버튼을 보여주게 됩니다.

폼 전송 시에는 해당 게시물의 번호 (primary key)를 input 타입 hidden으로 해서 넘겨주었습니다.

 

update.php (게시물의 내용을 불러와 수정)

<?php 
    include 'mysql.php'; //$con

    $filtered_num = mysqli_real_escape_string($con, $_GET['num']);

    $sql = "
        select * from board where num = $filtered_num;
    ";

    $result = mysqli_query($con,$sql);

    $row = mysqli_fetch_array($result);

    $filtered = [
        'date' => htmlspecialchars($row['date']),
        'title' => htmlspecialchars($row['title']),
        'content' => htmlspecialchars($row['content']),
        'writer' => htmlspecialchars($row['writer']),
    ];

    include 'header.php';
?>

    <form action="update2.php" method="POST">
        <p><input type="hidden" name="num" value="<?=$filtered_num?>"></p>
        <p>title : <input type="text" name="title" value="<?=$filtered['title']?>"></p>
        <p>content : <textarea name="content"><?=$filtered['content']?></textarea></p>
        <input type="submit" value="update">
    </form>

    <a href="list.php?num=<?=$filtered_num?>">cancel</a>

<?php 
    include 'footer.php';
?>

 

update2.php (DB에 수정)

<?php
    session_start();
    
    include 'mysql.php';
    
    $filtered_num = htmlspecialchars($_POST['num']);
    
    $filtered = [
        'title' => mysqli_real_escape_string($con, $_POST['title']),
        'content' => mysqli_real_escape_string($con, $_POST['content'])
    ];
    
    $sql = "
            update board
            set
                title = '{$filtered['title']}',
                content = '{$filtered['content']}',
                date = now(),
                writer = '{$_SESSION['id']}'
            where num = $filtered_num
        ";
    
    
    $result = mysqli_query($con, $sql);
    
    if ($result) {
        header("location: list.php?num=$filtered_num");
    } else {
        echo mysqli_error($con);
}

 

삭제 기능도 구현해보겠습니다.

delete.php

<?php 
    include 'mysql.php';

    $filtered_num = mysqli_real_escape_string($con,$_POST['num']);

    $sql = "
        delete from board
        where num = $filtered_num
    ";

    $result = mysqli_query($con,$sql);

    if($result){
        header("location: index.php");
    }else{
        echo mysqli_error($con);
    }
?>

삭제 버튼 클릭 시 delete.php 파일로 이동해 삭제 후 index.php로 돌아옵니다.

이렇게 해서 CRUD를 완성해보았네요👏