Home > Backend Development > PHP Tutorial > How to implement a real-time online question and answer system through PHP and WebSocket

How to implement a real-time online question and answer system through PHP and WebSocket

王林
Release: 2023-12-17 13:48:01
Original
1438 people have browsed it

How to implement a real-time online question and answer system through PHP and WebSocket

With the development of the Internet, real-time online interactive question and answer system has gradually become a common network application. It can not only meet the needs of users for real-time communication, but also enhance user stickiness and participation. In this article, we will use PHP and WebSocket as the basis to introduce how to implement a real-time online question and answer system, and provide specific code examples so that readers can better understand and learn.

1. What is WebSocket

WebSocket is a two-way communication standard based on the TCP protocol. It can establish a real-time connection between the web browser and the web server to realize real-time data transmission. Through WebSocket, we can push data from web applications to the client in real time, or receive real-time requests and responses from the client.

2. Why use WebSocket to implement a real-time online question and answer system

The traditional Ajax polling method has some problems in performance and stability, such as increasing server pressure and network delay. Using WebSocket can effectively optimize these questions and make the question and answer system more smooth and stable.

3. How to use PHP and WebSocket to implement a real-time online question and answer system

  1. Install WebSocket

We can use the PHP WebSocket class library to implement WebSocket. In this article, we use PHP WAMP server (https://wampserver.com/) to set up a development environment and install the PHP WebSocket class library (https://github.com/Textalk/websocket-php).

  1. Create WebSocket Server

Next, we need to create a WebSocket server to handle client requests. The WebSocket server needs to listen to the specified port and wait for the client to connect. When a client connects successfully, the server creates a WebSocket object and interacts with the client.

The following is a simple WebSocket server example:

use WebSocketServer;

$server = new Server('127.0.0.1', 8080);

$server->on('open', function($conn) {
    echo "New connection added: {$conn->getId()}
";
});

$server->on('message', function($conn, $msg) use ($server) {
    $server->broadcast($msg);
});

$server->run();
Copy after login

This code creates a WebSocket server instance and listens to port 127.0.0.1:8080. When a client connects successfully, the server will output the connection ID through the callback function, and broadcast it to all connected clients when receiving the client message.

  1. Create a question and answer system

Next, we need to create a question and answer system to handle user questions and answers. We can implement this system using PHP and MySQL.

First, we need to create a database to store questions and answers asked by users. The following is a sample SQL statement to create a data table:

CREATE TABLE `questions_info` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE `answers_info` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `question_id` int(11) NOT NULL,
  `content` text NOT NULL,
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Copy after login

This code creates two data tables to store detailed information about questions and answers. Among them, question_id is the ID of the answer to the question.

Next, we implement a question processing page for users to ask questions and view existing questions and answers in a web browser. When a user submits a question, we push the question information to all connected clients via WebSocket. When the client receives a new question, it will be displayed on the page.

The following is a simple sample code:

use WebSocketClient;

// 引入数据库连接信息
require_once 'config.php';

// 创建MySQL连接对象
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

// 处理用户提交问题
if (isset($_POST['submit'])) {
    $title = $mysqli->real_escape_string($_POST['title']);
    $content = $mysqli->real_escape_string($_POST['content']);
    $query = "INSERT INTO questions_info (title, content) VALUES ('$title', '$content')";
    $mysqli->query($query);
    $id = $mysqli->insert_id;

    // 推送新问题到客户端
    $client = new Client('ws://127.0.0.1:8080');
    $client->send('{"type":"new_question","id":'.$id.',"title":"'.$title.'","content":"'.$content.'"}');
}

// 查询已有问题
$query = "SELECT * FROM questions_info ORDER BY create_time DESC";
$result = $mysqli->query($query);

// 输出问题列表
while ($row = $result->fetch_assoc()) {
    $question_id = $row['id'];
    $question_title = $row['title'];
    $question_content = $row['content'];

    // 查询问题回答数
    $query = "SELECT COUNT(*) FROM answers_info WHERE question_id=$question_id";
    $answer_count = $mysqli->query($query)->fetch_row()[0];
?>

<div class="question-item">
    <h3 class="question-title">
        <a href="question.php?id=<?php echo $question_id; ?>"><?php echo $question_title; ?></a>
    </h3>
    <div class="question-content"><?php echo $question_content; ?></div>
    <div class="question-meta">
        <span class="answer-count"><?php echo $answer_count; ?>回答</span>
    </div>
</div>

<?php } ?>
Copy after login

This code implements the processing of user-initiated questions, and when pushing new questions to the client, passes JSON data through WebSocket so that customers can The client can handle new problems correctly.

Next, we implement an answer processing page. When the user submits an answer, the answer will be saved to the MySQL database and the answer information will be pushed to all connected clients through WebSocket. When the client receives a new answer, it will be displayed on the page.

The following is a simple sample code:

// 处理用户提交回答
if (isset($_POST['submit'])) {
    $question_id = $_POST['question_id'];
    $content = $mysqli->real_escape_string($_POST['content']);
    $query = "INSERT INTO answers_info (question_id, content) VALUES ('$question_id', '$content')";
    $mysqli->query($query);
    $id = $mysqli->insert_id;

    // 推送新回答到客户端
    $client = new Client('ws://127.0.0.1:8080');
    $client->send('{"type":"new_answer","id":'.$id.',"question_id":'.$question_id.',"content":"'.$content.'"}');
}

// 查询问题和回答列表
$question_id = $_GET['id'];
$query = "SELECT * FROM questions_info WHERE id=$question_id";
$question = $mysqli->query($query)->fetch_assoc();
$query = "SELECT * FROM answers_info WHERE question_id=$question_id ORDER BY create_time DESC";
$result = $mysqli->query($query);
?>

<h2 class="question-title"><?php echo $question['title']; ?></h2>
<div class="question-content"><?php echo $question['content']; ?></div>

<!-- 输出回答列表 -->
<?php while ($row = $result->fetch_assoc()) { ?>
<div class="answer-item">
    <div class="answer-content"><?php echo $row['content']; ?></div>
</div>
<?php } ?>

<!-- 输出回答表单 -->
<form method="post">
    <input type="hidden" name="question_id" value="<?php echo $question_id; ?>">
    <div class="form-item">
        <textarea name="content"></textarea>
    </div>
    <div class="form-item">
        <input type="submit" name="submit" value="提交回答">
    </div>
</form>
Copy after login

This code implements the processing of user answers to questions, and when pushing new answers to the client, passes JSON data through WebSocket so that the customer can The client can handle new responses correctly.

4. Summary

This article introduces how to use PHP and WebSocket to implement a real-time online question and answer system, and provides specific code examples. Through WebSocket, we can effectively optimize the performance and stability of the Q&A system, making it more enjoyable for users to use the system. At the same time, readers can also optimize their own web applications based on these sample codes and provide a better user experience.

The above is the detailed content of How to implement a real-time online question and answer system through PHP and WebSocket. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template