Home >Backend Development >PHP Problem >How to implement online communication function in php

How to implement online communication function in php

PHPz
PHPzOriginal
2023-04-19 09:18:35621browse

In the current Internet era, online communication has become an indispensable part of our daily lives. Whether at work or in life, we all need to communicate and interact with others online. Therefore, implementing an online communication function is becoming more and more important in today's website development. This article will introduce how to use PHP to implement a basic online communication function and provide complete code examples.

1. MySQL table design

Before you start writing PHP code, please design the database table structure according to your needs. For example, design a table structure named chat_message, which needs to store the following data:

  • Sender’s ID;
  • Receiver’s ID;
  • Message content;
  • Sending time.

Based on the above requirements, we need to design the following table structure:

CREATE TABLE `chat_message` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `from_user_id` int(11) unsigned NOT NULL,
  `to_user_id` int(11) unsigned NOT NULL,
  `message` varchar(255) DEFAULT '',
  `send_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Connect to MySQL database

In PHP, connecting to the MySQL database is very simple. We just need to use the mysqli_connect() function to connect to MySQL.

The following is an example of connecting to a MySQL database:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "chat_db";

// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);

// 检查连接是否成功
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

3. Insert chat message

When a user sends a chat message on the website, we need to insert the message into the database middle.

The following is a code example for inserting chat messages:

// 获取发送人ID和接收人ID
$from_user_id = $_SESSION['user_id'];
$to_user_id = $_POST['to_user_id'];
$message = $_POST['message'];

// 获取当前时间
$send_time = date('Y-m-d H:i:s');

// 将数据插入到 chat_message 表中
$sql = "INSERT INTO chat_message (from_user_id, to_user_id, message, send_time)
VALUES ('$from_user_id', '$to_user_id', '$message', '$send_time')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

4. Obtaining chat history

When the user views the chat history on the website, we need to obtain it from the database Historical news.

The following is a code example to obtain chat history records:

// 获取对话双方的ID
$user1_id = $_GET['user1_id'];
$user2_id = $_GET['user2_id'];

// 查询消息记录
$sql = "SELECT * FROM chat_message WHERE
        (from_user_id = '$user1_id' AND to_user_id = '$user2_id') OR
        (from_user_id = '$user2_id' AND to_user_id = '$user1_id')
        ORDER BY send_time ASC";
$result = mysqli_query($conn, $sql);

// 输出消息记录
while($row = mysqli_fetch_assoc($result)) {
    echo $row['send_time'] . " - " . $row['message'] . "<br>";
}

The above code will query the chat records related to the current user from the chat_message table, and output the message records in the order of sending time.

5. Implement web UI

Finally, we need to write a web UI to allow users to send and receive chat messages in the browser.

The following is a code example to implement a web UI:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>网上交流功能</title>
</head>
<body>
    <h1>网上交流功能</h1>
    <div id="chat_box" style="border: 1px solid black; height: 500px; overflow: auto;"></div>
    <br>
    <form id="message_form" action="" method="POST">
        接收人ID:<input type="text" name="to_user_id"><br><br>
        消息内容:<input type="text" name="message"><br><br>
        <input type="submit" value="发送">
    </form>

    <script>
        // 获取聊天记录
        setInterval(function() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("chat_box").innerHTML = this.responseText;
                }
            };
            xmlhttp.open("GET", "get_chat_history.php?user1_id="+user1_id+"&user2_id="+user2_id, true);
            xmlhttp.send();
        }, 1000);

        // 发送消息
        document.getElementById("message_form").addEventListener("submit", function(event) {
            event.preventDefault();
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    console.log(this.responseText);
                }
            };
            var data = new FormData(document.getElementById("message_form"));
            xmlhttp.open("POST", "insert_chat_message.php", true);
            xmlhttp.send(data);
            document.getElementById("message_form").reset();
        });
    </script>
</body>
</html>

The above code will create a web UI and allow users to send and receive messages by filling out forms. By using the setInterval() function to periodically query chat records and using the XMLHttpRequest object to send data to the server, we can check new chat records in real time. At the same time, by adding an event listener to the form using the addEventListener() function, we can capture user-submitted messages and insert them into the database.

6. Complete code

The following is a PHP code example for connecting to the MySQL database, inserting chat messages, and obtaining chat history.

connect_db.php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "chat_db";

// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);

// 检查连接是否成功
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

insert_chat_message.php

get_chat_history.php

The above is a complete code example of using PHP to implement online communication functions. Since this code example does not consider other aspects such as security, please pay attention to improvements and optimizations when using it.

The above is the detailed content of How to implement online communication function in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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