設(shè)計(jì)高效的PHP數(shù)據(jù)庫(kù)通常涉及以下幾個(gè)關(guān)鍵步驟和原則:
假設(shè)我們要設(shè)計(jì)一個(gè)簡(jiǎn)單的博客系統(tǒng),包含用戶表、文章表和評(píng)論表。
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);
// 創(chuàng)建文章
$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);
// 添加評(píng)論
$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();
}
?>
通過以上步驟和示例,你可以設(shè)計(jì)出一個(gè)高效、安全的PHP數(shù)據(jù)庫(kù)。