How to create a basic message board using PHP
The message board is a common website feature that allows users to leave their comments and opinions on the web page. In this article, we will introduce how to create a basic message board using PHP language. Below are specific code examples.
Create database
First, we need to create a database to store user messages. MySQL or other relational databases can be used. In this example, we use MySQL.
CREATE DATABASE message_board; USE message_board; CREATE TABLE messages ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, message TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
The above code creates a database namedmessage_board
, which contains a table namedmessages
for storing messages. The table structure includes the ID of the message record, user name, message content and creation time.
Create the front-end interface
Next, we create a simple front-end web page, let the user fill in the user name and message content, and submit it to the server.
The above code creates an HTML form that contains two fields: user name and message content. When the user clicks the submit button, the form data will be sent to thepost_message.php
file.
Processing submitted data
Next, we create apost_message.php
file to process the messages submitted by the user and save them to the database .
prepare($sql); $statement->execute([$name, $message]); // 返回主页 header('Location: index.html'); ?>
The above code first connects to the MySQL database, and then obtains the user name and message content submitted by the user. Next, it will insert this data into themessages
table and redirect the user back to the homepage via theheader
function.
Display message content
Finally, we create adisplay_messages.php
file to extract messages from the database and display them on the page.
query($sql); $messages = $statement->fetchAll(PDO::FETCH_ASSOC); // 显示留言内容 foreach ($messages as $message) { echo '' . $message['name'] . ': ' . $message['message'] . '
'; } ?>
The above code first connects to the database, then queries themessages
table, and saves the results in the$messages
variable. Then, it uses a loop to display the content of each message on the page.
At this point, we have completed the creation of a basic message board. Users can fill in messages on the front-end page, and the background will store the message content in the database and display it on the home page. This is just a simple example, you can modify and extend it according to your actual needs. I hope this article can help you get started with PHP development and create your own message board function.
The above is the detailed content of How to create a basic message board using PHP. For more information, please follow other related articles on the PHP Chinese website!