php에 mysql 연동

날아올라돼지야·2024년 9월 23일
0

리눅스 마스터 과정

목록 보기
31/31

PHP 게시판 애플리케이션을 MySQL 데이터베이스와 연동하도록 수정하겠습니다. 이 버전에서는 게시글 데이터를 MySQL에 저장하고, 게시글을 추가, 수정, 삭제하는 기능을 데이터베이스와 연동하여 처리합니다.

1. MySQL 데이터베이스 설정

1) MySQL 설치 및 설정

MySQL이 설치되어 있지 않다면, 다음 명령어로 MySQL을 설치합니다.

sudo apt update
sudo apt install mysql-server

설치 후 MySQL을 실행합니다.

sudo systemctl start mysql

2) 데이터베이스 및 테이블 생성

MySQL에 접속하여 게시판을 위한 데이터베이스와 테이블을 생성합니다.

sudo mysql -u root -p

MySQL에 접속한 후, 다음 명령어로 데이터베이스와 테이블을 생성합니다.

CREATE DATABASE php_board_db;
USE php_board_db;

CREATE TABLE posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

이 명령어는 php_board_db라는 데이터베이스와 posts라는 게시글 테이블을 생성합니다.

3) MySQL 사용자 생성 및 권한 부여

다음 명령어로 데이터베이스에 사용할 사용자를 생성하고 권한을 부여합니다.

CREATE USER 'php_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON php_board_db.* TO 'php_user'@'localhost';
FLUSH PRIVILEGES;

2. PHP 게시판 애플리케이션 수정 (MySQL 연동)

이제 PHP 게시판 애플리케이션을 MySQL과 연동하도록 수정하겠습니다.

1) PHP MySQLi 확장 설치

PHP와 MySQL 연동을 위해 MySQLi 또는 PDO 확장이 필요합니다. PHP MySQL 확장을 설치합니다.

sudo apt install php-mysql
sudo systemctl restart apache2

2) index.php 코드 수정

다음은 MySQL과 연동된 PHP 게시판 코드입니다. 게시글 추가, 수정, 삭제가 모두 MySQL 데이터베이스와 연동되도록 작성되었습니다.

<?php
// MySQL 데이터베이스 연결 설정
$host = 'localhost';
$dbname = 'php_board_db';
$username = 'php_user';
$password = 'password';

// MySQL에 연결
$mysqli = new mysqli($host, $username, $password, $dbname);

// 연결 오류 확인
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// 게시글 추가 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $title = htmlspecialchars($_POST['title']);
    $content = htmlspecialchars($_POST['content']);
    $stmt = $mysqli->prepare("INSERT INTO posts (title, content) VALUES (?, ?)");
    $stmt->bind_param("ss", $title, $content);
    $stmt->execute();
    $stmt->close();
    header('Location: index.php');
    exit();
}

// 게시글 수정 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id = intval($_POST['id']);
    $title = htmlspecialchars($_POST['title']);
    $content = htmlspecialchars($_POST['content']);
    $stmt = $mysqli->prepare("UPDATE posts SET title = ?, content = ? WHERE id = ?");
    $stmt->bind_param("ssi", $title, $content, $id);
    $stmt->execute();
    $stmt->close();
    header('Location: index.php');
    exit();
}

// 게시글 삭제 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $id = intval($_POST['id']);
    $stmt = $mysqli->prepare("DELETE FROM posts WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();
    header('Location: index.php');
    exit();
}

// 게시글 목록 조회
$result = $mysqli->query("SELECT * FROM posts ORDER BY created_at DESC");
$posts = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>PHP 게시판</title>
</head>
<body>
    <h1>PHP 게시판</h1>

    <!-- 게시글 작성 폼 -->
    <form method="POST" action="index.php">
        <input type="hidden" name="action" value="add">
        <label for="title">제목:</label><br>
        <input type="text" id="title" name="title" required><br><br>
        
        <label for="content">내용:</label><br>
        <textarea id="content" name="content" required></textarea><br><br>
        
        <input type="submit" value="게시글 등록">
    </form>

    <h2>게시글 목록</h2>

    <?php if (!empty($posts)): ?>
        <?php foreach ($posts as $post): ?>
            <div>
                <h3><?= htmlspecialchars($post['title']) ?></h3>
                <p><?= nl2br(htmlspecialchars($post['content'])) ?></p>
                <small>작성일: <?= $post['created_at'] ?></small>

                <!-- 수정 폼 -->
                <form method="POST" action="index.php" style="display:inline;">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" value="<?= $post['id'] ?>">
                    <label for="title-<?= $post['id'] ?>">제목:</label>
                    <input type="text" id="title-<?= $post['id'] ?>" name="title" value="<?= htmlspecialchars($post['title']) ?>" required><br>
                    <label for="content-<?= $post['id'] ?>">내용:</label>
                    <textarea id="content-<?= $post['id'] ?>" name="content" required><?= htmlspecialchars($post['content']) ?></textarea><br>
                    <input type="submit" value="수정">
                </form>

                <!-- 삭제 폼 -->
                <form method="POST" action="index.php" style="display:inline;">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= $post['id'] ?>">
                    <input type="submit" value="삭제" onclick="return confirm('정말로 삭제하시겠습니까?');">
                </form>

                <hr>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>게시글이 없습니다.</p>
    <?php endif; ?>
</body>
</html>

코드 설명

  1. MySQL 연결:

    • mysqli 확장을 사용하여 MySQL 데이터베이스에 연결합니다.
    • 데이터베이스 연결에 필요한 호스트, 사용자 이름, 비밀번호, 데이터베이스 이름을 설정합니다.
  2. 게시글 추가:

    • POST 요청으로 받은 제목과 내용을 MySQL 데이터베이스에 추가합니다.
  3. 게시글 수정:

    • 게시글 수정 요청이 들어오면 해당 게시글의 제목과 내용을 업데이트합니다.
  4. 게시글 삭제:

    • 특정 게시글을 삭제할 수 있는 기능을 제공합니다.
  5. 게시글 조회:

    • MySQL에서 모든 게시글을 내림차순으로 조회하여 출력합니다.

3. Apache 디렉토리 권한 설정

Apache가 MySQL과 연동된 PHP 게시판을 처리할 수 있도록 디렉토리 권한을 설정합니다.

sudo chown -R www-data:www-data /var/www/html/php-board
sudo chmod -R 755 /var/www/html/php-board

4. PHP 게시판 실행 및 테스트

이제 브라우저에서 게시판 애플리케이션을 실행하고 MySQL과 연동된 게시판을 사용할 수 있습니다. 브라우저에서 http://localhost/php-board/ 또는 http://<서버_IP>/php-board/에 접속하여 게시판을 테스트할 수 있습니다.


요약

  1. MySQL 설정: 게시글을 저장할 데이터베이스와 테이블을 생성합니다.
  2. PHP MySQL 연동: PHP 게시판 애플리케이션을 수정하여 MySQL과 연동합니다.
  3. 게시글 추가, 수정, 삭제: MySQL을 통해 게시글을 처리할 수 있는 CRUD 기능을 구현했습니다.

이 게시판은 기본적인 CRUD 기능을 제공하며, 데이터베이스로 MySQL을 사용하는 간단한 애플리케이션입니다.

profile
무슨 생각하며 사니

0개의 댓글

관련 채용 정보