php内容管理系统代码
时间: 2023-09-30 07:04:22 浏览: 30
以下是一个简单的 PHP 内容管理系统的代码示例,包括添加、修改、删除和显示内容:
index.php:
```php
<?php
// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");
// 处理表单提交
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$content = $_POST['content'];
// 添加内容到数据库
$sql = "INSERT INTO posts (title, content) VALUES ('$title', '$content')";
mysqli_query($conn, $sql);
}
// 删除内容
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
$sql = "DELETE FROM posts WHERE id=$id";
mysqli_query($conn, $sql);
}
// 获取所有内容
$sql = "SELECT * FROM posts";
$result = mysqli_query($conn, $sql);
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>内容管理系统</title>
</head>
<body>
<h1>所有内容</h1>
<?php if (!empty($posts)): ?>
<ul>
<?php foreach ($posts as $post): ?>
<li>
<h2><?php echo $post['title']; ?></h2>
<p><?php echo $post['content']; ?></p>
<a href="index.php?delete=<?php echo $post['id']; ?>">删除</a>
<a href="edit.php?id=<?php echo $post['id']; ?>">编辑</a>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p>没有内容。</p>
<?php endif; ?>
<h2>添加内容</h2>
<form method="post">
<label for="title">标题:</label>
<input type="text" name="title" id="title">
<label for="content">内容:</label>
<textarea name="content" id="content"></textarea>
<input type="submit" name="submit" value="添加">
</form>
</body>
</html>
```
edit.php:
```php
<?php
// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");
// 获取要编辑的内容
$id = $_GET['id'];
$sql = "SELECT * FROM posts WHERE id=$id";
$result = mysqli_query($conn, $sql);
$post = mysqli_fetch_assoc($result);
// 处理表单提交
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$content = $_POST['content'];
// 更新内容到数据库
$sql = "UPDATE posts SET title='$title', content='$content' WHERE id=$id";
mysqli_query($conn, $sql);
// 返回首页
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>编辑内容</title>
</head>
<body>
<h1>编辑内容</h1>
<form method="post">
<label for="title">标题:</label>
<input type="text" name="title" id="title" value="<?php echo $post['title']; ?>">
<label for="content">内容:</label>
<textarea name="content" id="content"><?php echo $post['content']; ?></textarea>
<input type="submit" name="submit" value="保存">
</form>
</body>
</html>
```