加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php结合mysql及ajax实现的聊天室源码

发布时间:2020-05-25 22:28:42 所属栏目:PHP 来源:互联网
导读:最近编写了一个php版的网页聊天室(结合了mysql数据库和ajax知识),自己纯手工完成的,功能相似与QQ,但网页界面没有优化,因为主要是用于学习,懂得原理我觉得才是最重要的。里面没有很深奥的技术,所以很适合初学者学习,需要的朋友可以参考一下本文章的源

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("www.manongjc.com","databasename","password")

or die('无法连接: ' . mysql_error());

mysql_select_db("databasename") or die('没有你找到指定数据库');

return true;

}

function quote($strText)

{

/* 作者:脚本之家教程 http://www.manongjc.com */

$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",$_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

/* 作者:脚本之家教程 http://www.manongjc.com/article/1548.html */

$msg="

";

while ($line = mysql_fetch_array($result,MYSQL_ASSOC))

{

$msg = $msg . "

"

"

}

$msg=$msg . "

echo $msg;

?>

4.聊天室页面:

chat.html

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

聊天页面

border-left: black thin solid; border-bottom: black thin solid;

background:#fff url('http://www.ihaonet.com/chat/blue.jpg') repeat-x left top;

height: 450px;width: 500px; ">

text-align: center">

聊天窗口--全球最大QQ聊天交友网站 (作者:脚本之家教程 http://www.manongjc.com )

text-align: left">

名字:

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!