PHP是一种广泛使用的开源脚本语言,尤其适用于Web开发。MySQL是一种关系型数据库管理系统,用于存储和管理数据。在线聊天系统是一个允许用户实时交流的网络应用程序。
在线聊天系统可以分为以下几种类型:
以下是一个简单的PHP + MySQL在线聊天系统的示例代码:
CREATE TABLE `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sender` varchar(255) NOT NULL,
`receiver` varchar(255) NOT NULL,
`message` text NOT NULL,
`timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "chatdb";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];
$sql = "INSERT INTO messages (sender, receiver, message) VALUES ('$sender', '$receiver', '$message')";
if ($conn->query($sql) === TRUE) {
echo "消息发送成功";
} else {
echo "错误: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "chatdb";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$receiver = $_GET['receiver'];
$sql = "SELECT * FROM messages WHERE receiver = '$receiver' ORDER BY timestamp DESC LIMIT 50";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<b>" . $row["sender"] . "</b>: " . $row["message"] . "<br>";
}
} else {
echo "没有消息";
}
$conn->close();
?>
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云