設計高效的PHP數據庫通常涉及以下幾個關鍵步驟和原則:
假設我們要設計一個簡單的博客系統,包含用戶表、文章表和評論表。
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
article_id INT NOT NULL,
user_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (article_id) REFERENCES articles(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
<?php
$dsn = 'mysql:host=localhost;dbname=blog';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 創建文章
$stmt = $pdo->prepare("INSERT INTO articles (user_id, title, content) VALUES (?, ?, ?)");
$stmt->execute([1, 'Sample Title', 'Sample Content']);
// 獲取文章
$stmt = $pdo->prepare("SELECT * FROM articles WHERE id = ?");
$stmt->execute([1]);
$article = $stmt->fetch(PDO::FETCH_ASSOC);
// 添加評論
$stmt = $pdo->prepare("INSERT INTO comments (article_id, user_id, content) VALUES (?, ?, ?)");
$stmt->execute([$article['id'], 1, 'Great article!']);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
通過以上步驟和示例,你可以設計出一個高效、安全的PHP數據庫。