PHP 게시판 애플리케이션을 MySQL 데이터베이스와 연동하도록 수정하겠습니다. 이 버전에서는 게시글 데이터를 MySQL에 저장하고, 게시글을 추가, 수정, 삭제하는 기능을 데이터베이스와 연동하여 처리합니다.
MySQL이 설치되어 있지 않다면, 다음 명령어로 MySQL을 설치합니다.
sudo apt update
sudo apt install mysql-server
설치 후 MySQL을 실행합니다.
sudo systemctl start mysql
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
라는 게시글 테이블을 생성합니다.
다음 명령어로 데이터베이스에 사용할 사용자를 생성하고 권한을 부여합니다.
CREATE USER 'php_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON php_board_db.* TO 'php_user'@'localhost';
FLUSH PRIVILEGES;
이제 PHP 게시판 애플리케이션을 MySQL과 연동하도록 수정하겠습니다.
PHP와 MySQL 연동을 위해 MySQLi 또는 PDO 확장이 필요합니다. PHP MySQL 확장을 설치합니다.
sudo apt install php-mysql
sudo systemctl restart apache2
다음은 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>
MySQL 연결:
mysqli
확장을 사용하여 MySQL 데이터베이스에 연결합니다.게시글 추가:
게시글 수정:
게시글 삭제:
게시글 조회:
Apache가 MySQL과 연동된 PHP 게시판을 처리할 수 있도록 디렉토리 권한을 설정합니다.
sudo chown -R www-data:www-data /var/www/html/php-board
sudo chmod -R 755 /var/www/html/php-board
이제 브라우저에서 게시판 애플리케이션을 실행하고 MySQL과 연동된 게시판을 사용할 수 있습니다. 브라우저에서 http://localhost/php-board/ 또는 http://<서버_IP>/php-board/에 접속하여 게시판을 테스트할 수 있습니다.
이 게시판은 기본적인 CRUD 기능을 제공하며, 데이터베이스로 MySQL을 사용하는 간단한 애플리케이션입니다.