php mysql个人博客
时间: 2024-01-02 19:23:05 浏览: 137
PHP和MySQL是一对非常常用的技术组合,用于开发动态网站和应用程序。个人博客是一种常见的网站类型,让用户可以创建和分享自己的博客文章。PHP个人博客系统是基于PHP和MySQL开发的一种个性化的博客系统,可以满足用户对个性化博客的需求。
以下是一个简单的PHP MySQL个人博客系统的示例:
1. 创建数据库和表:
```sql
CREATE DATABASE blog;
USE blog;
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
2. 创建博客页面(index.php):
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
// 获取博客文章
$sql = "SELECT * FROM posts ORDER BY created_at DESC";
$result = $conn->query($sql);
// 显示博客文章
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<p>" . $row["content"] . "</p>"; echo "<p>Created at: " . $row["created_at"] . "</p>";
echo "<hr>";
}
} else {
echo "No posts found.";
}
// 关闭数据库连接
$conn->close();
?>
```
3. 创建添加博客文章页面(add_post.php):
```php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
// 获取表单数据
$title = $_POST["title"];
$content = $_POST["content"];
// 插入博客文章
$sql = "INSERT INTO posts (title, content) VALUES ('$title', '$content')";
if ($conn->query($sql) === TRUE) {
echo "Post added successfully.";
} else {
echo "Error adding post: " . $conn->error;
}
// 关闭数据库连接
$conn->close();
}
?>
<form method="POST" action="add_post.php">
<label for="title">Title:</label>
<input type="text" name="title" id="title" required><br>
<label for="content">Content:</label>
<textarea name="content" id="content" required></textarea><br>
<input type="submit" value="Add Post">
</form>
```
这个示例演示了一个简单的PHP MySQL个人博客系统,用户可以在网页上查看已发布的博客文章,并通过添加博客文章页面添加新的博客文章。
阅读全文