티스토리 뷰

다음은 글쓰기 버튼을 클릭했을 때 새로운 글을 작성할 수 있는 코드입니다.

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

 

create.php

<?php 
    include 'header.php';
?>
    <h1><a href="index.php">Board</a></h1>

    <form action="create2.php" method="POST">
        <p><input type="text" name="title" placeholder="title"></p>
        <textarea name="content" placeholder="content"></textarea>
        <p><input type="submit" value="submit"></p>
    </form>

    <a href="index.php">cancel</a>

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

작성한 게시물을 create2.php 파일로 폼 전송해줍니다.

 

create2.php

<?php 
    include 'mysql.php'; //DB 연결하는 코드 $con

    session_start();    

    $filtered = [
        "title" => mysqli_real_escape_string($con,$_POST['title']),
        "content" => mysqli_real_escape_string($con,$_POST['content'])
    ];

    $sql = "
        insert into board(
            title, writer, content, date
        )
        values(
            '{$filtered['title']}',
            '{$_SESSION['id']}',
            '{$filtered['content']}',
            now()
        )
    ";

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

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

form으로 받아오면 게시물의 데이터를 테이블에 저장합니다.

글 작성이 완료되었다면 게시물을 보여줍시다.

 

index.php

<?php
include 'mysql.php'; //DB 연결 $con
include 'header.php';
$sql = "select * from board";
$result = mysqli_query($con,$sql);
?>

<?php
if (empty($_SESSION['id'])) {
?>
    <a href='login.php'>login</a>
    <a href='resister.php'>signup</a>
<?php
} else {
?>
    <span>Welcome, <?= $_SESSION['id'] ?>!</span>
    <a href='create.php'>write</a>
    <a href='logout.php'>logout</a>
    <a href="change_info.php">info</a>
<?php
}
?>

<h1><a href="index.php">Board</a></h1><br>

<table>
    <tr>
        <td>날짜</td>
        <td style="width:200px">글제목</td>
        <td>작성자</td>
    </tr>

    <?php
        while ($row = mysqli_fetch_array($result)) {
            $filtered = [
                'date' => date('m-d', strtotime(htmlspecialchars($row['date']))),
                'title' => htmlspecialchars($row['title']),
                'writer' => htmlspecialchars($row['writer']),
                'num' => htmlspecialchars($row['num'])
            ];
        }
    ?>
            <tr>
                <td><?= $filtered['date'] ?></td>
                <td><a href="list.php?num=<?= $filtered['num'] ?>"><?= $filtered['title'] ?></a></td>
                <td><?= $filtered['writer'] ?></td>
            </tr>
      <?php
        }
      ?>
</table>

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

테이블에 저장된 게시물을 모두 확인할 수 있습니다.

다음은 삭제, 수정하는 기능을 넣어보겠습니다.