php结合mysql及ajax实现的聊天室源码
|
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="
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; ">
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
||||||||||||||
