最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
PHP+mysql+ajax轻量级聊天室
时间:2022-06-24 22:44:53 编辑:袖梨 来源:一聚教程网
本文实例讲述了PHP+mysql+ajax轻量级聊天室实现方法。分享给大家供大家参考,具体如下:
做了一个QQ聊天交友网站,想加个聊天的功能,于是做完用PHP做了简单又强大的聊天室
1. 创建mysql数据库表:
create table chat( id bigint AUTO_INCREMENT,username varchar(20), chatdate datetime,msg varchar(500), primary key(id));
2.编写建议连接数据库函数:
dbconnect.php
function db_connect()
{
date_default_timezone_set("Asia/Shanghai");
$link = mysql_connect("xxx.xxx.xxx.xxx", "databasename", "password")
or die('无法连接: ' . mysql_error());
mysql_select_db("databasename") or die('没有你找到指定数据库');
return true;
}
function quote($strText)
{
$Mstr = addslashes($strText);
return "'" . $Mstr . "'";
}
function isdate($d)
{
$ret = true;
try
{
$x = date("d",$d);
}
catch (Exception $e)
{
$ret = false;
}
echo $x;
return $ret;
}
?>
3. 编写ajax发送和接收函数:
ajax发送函数chat_send_ajax.php
require_once('dbconnect.php');
db_connect();
$msg = iconv("UTF-8","GB2312",$_GET["msg"]);
$dt = date("Y-m-d H:i:s");
$user = iconv("UTF-8","GB2312",$_GET["name"]);
$sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " .
"values(" . quote($user) . "," . quote($dt) . "," . quote($msg) . ");";
echo $sql;
$result = mysql_query($sql);
if(!$result)
{
throw new Exception('Query failed: ' . mysql_error());
exit();
}
?>
ajax接收函数chat_recv_ajax.php
header("Content-Type:text/html;charset=gb2312");
header("Expires: Thu, 01 Jan 1970 00:00:01 GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
require_once('dbconnect.php');
db_connect();
$sql = "SELECT *, date_format(chatdate,'%Y年%m月%d日 %r') as cdt from chat order by ID desc limit 200";
$sql = "SELECT * FROM (" . $sql . ") as ch order by ID";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
// Update Row Information
$msg="
" . $line["cdt"] . " | " ." . $line["username"] . ": | " ." . $line["msg"] . " |
echo $msg;
?>
4.聊天室页面:
chat.html
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
聊天窗口--全球最大QQ聊天交友网站 | |||
| |||
效果图如下:
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22