search
HomeBackend DevelopmentPHP ProblemHow to implement online communication function in php

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:

nbsp;html>


    <meta>
    <title>网上交流功能</title>


    <h1 id="网上交流功能">网上交流功能</h1>
    <div></div>
    <br>
    
        接收人ID:

        消息内容:

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

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

<?php require_once(&#39;connect_db.php&#39;);

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

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

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

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

get_chat_history.php

<?php require_once(&#39;connect_db.php&#39;);

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

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

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

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)