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><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('connect_db.php'); // 获取发送人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); } ?>
get_chat_history.php
<?php require_once('connect_db.php'); // 获取对话双方的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 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!

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

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.

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.

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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
God-level code editing software (SublimeText3)