How to write a simple online guest message system through PHP
With the popularity and development of the Internet, websites have become an important tool for people to obtain information and communicate. In order to communicate with visitors, many websites provide message systems. This article will introduce how to use PHP to write a simple online guest message system and provide specific code examples.
messages
: CREATE TABLE messages ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL, message TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
<form method="POST" action="submit.php"> <label for="name">姓名:</label> <input type="text" id="name" name="name" required> <label for="email">邮箱:</label> <input type="email" id="email" name="email" required> <label for="message">留言:</label> <textarea id="message" name="message" required></textarea> <button type="submit">提交留言</button> </form>
submit.php
: <?php // 连接数据库 $db_host = '数据库主机'; $db_name = '数据库名字'; $db_user = '数据库用户名'; $db_pass = '数据库密码'; $conn = new mysqli($db_host, $db_user, $db_pass, $db_name); if ($conn->connect_error) { die('数据库连接失败: ' . $conn->connect_error); } // 处理留言提交 if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $sql = "INSERT INTO messages (name, email, message) VALUES ('$name', '$email', '$message')"; if ($conn->query($sql) === TRUE) { echo '留言提交成功'; } else { echo '留言提交失败: ' . $conn->error; } } // 关闭数据库连接 $conn->close(); ?>
list.php
: <?php // 连接数据库 $db_host = '数据库主机'; $db_name = '数据库名字'; $db_user = '数据库用户名'; $db_pass = '数据库密码'; $conn = new mysqli($db_host, $db_user, $db_pass, $db_name); if ($conn->connect_error) { die('数据库连接失败: ' . $conn->connect_error); } // 查询留言列表 $sql = "SELECT * FROM messages ORDER BY created_at DESC"; $result = $conn->query($sql); // 显示留言列表 if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo '姓名: ' . $row['name'] . '<br>'; echo '邮箱: ' . $row['email'] . '<br>'; echo '留言: ' . $row['message'] . '<br>'; echo '时间: ' . $row['created_at'] . '<hr>'; } } else { echo '暂无留言'; } // 关闭数据库连接 $conn->close(); ?>
Through the above steps, we have successfully written a simple online guest message system using PHP. Visitors can submit messages through the form, and the messages will be saved in the database and displayed in the message list. You can further expand the functionality according to your needs, such as adding editing and deletion functions for messages. Hope this article can be helpful to you!
The above is the detailed content of How to write a simple online guest message system through PHP. For more information, please follow other related articles on the PHP Chinese website!