用PHP和mysql写一个简易论坛网站,功能包括用户的登录注册与更改密码,帖子的发表回复与删除。给出完整代码并说明PHP文件名。并给出表创建代码
时间: 2024-05-16 11:14:49 浏览: 90
以下是简易论坛网站的PHP和MySQL代码实现,文件名为index.php:
```php
<?php
session_start();
include('config.php');
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $username;
header('location: home.php');
} else {
echo "Invalid username or password.";
}
}
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($conn, $query);
}
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location: index.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple Forum - Home</title>
</head>
<body>
<header>
<h1>Simple Forum</h1>
<nav>
<ul>
<?php if(isset($_SESSION['username'])) { ?>
<li>Welcome, <?php echo $_SESSION['username']; ?></li>
<li><a href="create_post.php">Create Post</a></li>
<li><a href="logout.php">Logout</a></li>
<?php } else { ?>
<li><a href="login.php">Login</a></li>
<li><a href="register.php">Register</a></li>
<?php } ?>
</ul>
</nav>
</header>
<main>
<h2>Recent Posts</h2>
<?php
$query = "SELECT * FROM posts ORDER BY date DESC";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
echo "<h3><a href='view_post.php?id=".$row['id']."'>".$row['title']."</a></h3>";
echo "<p>".$row['content']."</p>";
echo "<p>Posted by ".$row['author']." on ".$row['date']."</p>";
echo "<hr>";
}
?>
</main>
<footer>
<p>© 2021 Simple Forum</p>
</footer>
</body>
</html>
```
config.php文件内容如下:
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "forum";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
```
创建数据库和表的SQL语句:
```sql
CREATE DATABASE forum;
USE forum;
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(32) NOT NULL
);
CREATE TABLE posts (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
author VARCHAR(30) NOT NULL,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```
以上代码实现了简易论坛网站的登录、注册、发表帖子、回复帖子和删除帖子等功能。
阅读全文