Apabila orang semakin bergantung kepada Internet, bilik sembang dalam talian masa nyata telah menjadi ciri standard bagi kebanyakan tapak web. Artikel ini akan memperkenalkan cara menggunakan PHP untuk melaksanakan ruang sembang dalam talian masa nyata asas.
Sebelum anda mula, pastikan persekitaran anda mempunyai syarat berikut:
CREATE DATABASE chat; USE chat; CREATE TABLE messages ( id INT(11) AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, message TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP );
<!DOCTYPE html> <html> <head> <title>Online Chat Room</title> <link rel="stylesheet" type="text/css" href="chat.css"> </head> <body> <div class="chat-container"> <div class="chat-header"> <h2>Chat Room</h2> </div> <div class="chat-messages"></div> <div class="chat-form"> <form> <input type="text" name="username" placeholder="Username" required> <input type="text" name="message" placeholder="Type your message here" required> <button type="submit">Send</button> </form> </div> </div> <script src="jquery.min.js"></script> <script src="chat.js"></script> </body> </html>
body { margin: 0; padding: 0; font-family: Arial, sans-serif; } .chat-container { width: 80%; margin: 50px auto; border: 1px solid #ccc; box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.1); } .chat-header { padding: 10px; background-color: #eee; } .chat-header h2 { margin: 0; font-size: 18px; } .chat-messages { height: 300px; overflow: auto; padding: 10px; } .chat-form { padding: 10px; } .chat-form form { display: flex; flex-wrap: wrap; } .chat-form input { flex: 1; margin: 0 5px 0 0; padding: 10px; border: none; border-radius: 3px; } .chat-form button { flex-basis: 100px; padding: 10px; background-color: #0099ff; color: #fff; border: none; border-radius: 3px; cursor: pointer; transition: background-color 0.2s; } .chat-form button:hover { background-color: #0088cc; }
<?php /* 设置响应格式为JSON */ header('Content-Type: application/json'); /* 连接数据库 */ define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', '123456'); define('DB_NAME', 'chat'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); /* 检查数据库连接是否成功 */ if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } /* 处理消息发送请求 */ if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $message = $_POST['message']; $sql = "INSERT INTO messages (username, message) VALUES ('$username', '$message')"; if (mysqli_query($conn, $sql)) { echo json_encode(['status' => 'success']); } else { echo json_encode(['status' => 'error', 'message' => mysqli_error($conn)]); } } else { /* 处理消息获取请求 */ $last_id = $_GET['last_id']; $sql = "SELECT * FROM messages WHERE id > $last_id ORDER BY created_at ASC"; $result = mysqli_query($conn, $sql); $messages = []; while ($row = mysqli_fetch_assoc($result)) { $messages[] = $row; } echo json_encode(['status' => 'success', 'messages' => $messages]); } mysqli_close($conn);
$(function() { /* 存储最后一条消息的ID */ var last_id = 0; /* 获取所有消息 */ function getMessages() { $.get('chat.php', {'last_id': last_id}, function(data) { if (data.status == 'success') { /* 迭代所有消息并添加到聊天室中 */ $.each(data.messages, function(index, message) { var html = '<p><strong>' + message.username + ':</strong> ' + message.message + '</p>'; $('.chat-messages').append(html); /* 更新最后一条消息的ID */ last_id = message.id; }); /* 滚动到底部以显示最新的消息 */ $('.chat-messages').scrollTop($('.chat-messages')[0].scrollHeight); } }, 'json'); } /* 获取所有消息 */ getMessages(); /* 处理消息发送表单的提交事件 */ $('.chat-form form').submit(function(e) { e.preventDefault(); /* 获取表单输入 */ var username = $('input[name="username"]').val(); var message = $('input[name="message"]').val(); /* 发送AJAX请求 */ $.post('chat.php', {'username': username, 'message': message}, function(data) { if (data.status == 'success') { /* 清空输入框 */ $('input[name="message"]').val(''); } else { /* 处理错误 */ alert('Error: ' + data.message); } }, 'json'); }); /* 每5秒获取一次消息 */ setInterval(getMessages, 5000); });
Atas ialah kandungan terperinci Bagaimana untuk melaksanakan ruang sembang dalam talian menggunakan PHP. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!