PHP+mysql+ajax轻量级聊天室实现方法详解


Posted in PHP onOctober 17, 2016

本文实例讲述了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

<?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

<?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

<?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="<table border='0' style='font-size: 10pt; color: white; font-family: verdana, arial;'>";
   while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
   {
      $msg = $msg . "<tr><td>" . $line["cdt"] . " </td>" .
        "<td>" . $line["username"] . ": </td>" .
        "<td>" . $line["msg"] . "</td></tr>";
   }
   $msg=$msg . "</table>";
   echo $msg;
?>

4.聊天室页面:

chat.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  <title>聊天页面</title>
<script type="text/javascript">
var t = setInterval(function(){get_chat_msg()},5000);
//
// General Ajax Call
//
var oxmlHttp;
var oxmlHttpSend;
function get_chat_msg()
{
  if(typeof XMLHttpRequest != "undefined")
  {
    oxmlHttp = new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    oxmlHttp = new ActiveXObject("Microsoft.XMLHttp");
  }
  if(oxmlHttp == null)
  {
    alert("浏览器不支持XML Http Request!");
    return;
  }
  oxmlHttp.onreadystatechange = get_chat_msg_result;
  oxmlHttp.open("GET",encodeURI("chat_recv_ajax.php"),true);
  oxmlHttp.send(null);
}
function get_chat_msg_result()
{
  if(oxmlHttp.readyState==4 || oxmlHttp.readyState=="complete")
  {
    if (document.getElementById("DIV_CHAT") != null)
    {
      document.getElementById("DIV_CHAT").innerHTML = oxmlHttp.responseText;
      oxmlHttp = null;
    }
    var scrollDiv = document.getElementById("DIV_CHAT");
    scrollDiv.scrollTop = scrollDiv.scrollHeight;
  }
}
function set_chat_msg()
{
  if(typeof XMLHttpRequest != "undefined")
  {
    oxmlHttpSend = new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
  }
  if(oxmlHttpSend == null)
  {
    alert("浏览器不支持XML Http Request!");
    return;
  }
  var url = "chat_send_ajax.php";
  var strname="noname";
  var strmsg="";
  if (document.getElementById("txtname") != null)
  {
    strname = document.getElementById("txtname").value;
    document.getElementById("txtname").readOnly=true;
  }
  if (document.getElementById("txtmsg") != null)
  {
    strmsg = document.getElementById("txtmsg").value;
    document.getElementById("txtmsg").value = "";
  }
  url += "?name=" + strname + "&msg=" + strmsg;
  oxmlHttpSend.open("GET",encodeURI(url),true);
  oxmlHttpSend.send(null);
}
function clickBtn(e)
 {
  if(window.event.keyCode==13)
  {
  var id=e.id;
  switch(id)
  {
   case "txtmsg":
   document.getElementById("Submit2").click();
   window.event.returnValue=false;
   break;
   }
  }
}
function fRandomBy(under, over){
switch(arguments.length){
case 1: return parseInt(Math.random()*under+1);
case 2: return parseInt(Math.random()*(over-under+1) + under);
default: return 0;
}
}
function SetTxtName(){
var i=fRandomBy(10);
if(i==0)document.getElementById('txtname').value='无敌战神';
if(i==1)document.getElementById('txtname').value='令狐冲';
if(i==2)document.getElementById('txtname').value='西门吹雪';
if(i==3)document.getElementById('txtname').value='超级玛丽';
if(i==4)document.getElementById('txtname').value='奥巴马';
if(i==5)document.getElementById('txtname').value='恐怖分子';
if(i==6)document.getElementById('txtname').value='聊斋奇女子';
if(i==7)document.getElementById('txtname').value='天朝?潘?;
if(i==8)document.getElementById('txtname').value='中500万了';
if(i==9)document.getElementById('txtname').value='神级奇葩';
if(i==10)document.getElementById('txtname').value='爱你不是两三天';
}
</script>
</head>
<body onload="SetTxtName();">
  <div style="border-right: black thin solid; border-top: black thin solid;
    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; ">
    <table style="width:100%; height:100%">
      <tr>
        <td colspan="2" style="font-weight: bold; font-size: 16pt; color: white; font-family: verdana, arial;
          text-align: center">
          聊天窗口--全球最大QQ聊天交友网站</td>
      </tr>
      <tr>
        <td colspan="2" style="font-weight: bold; font-size: 16pt; color: white; font-family: verdana, arial;
          text-align: left">
          <table style="font-size: 12pt; color: white; font-family: Verdana, Arial;border: white thin solid; ">
            <tr>
              <td style="width: 100px">
                名字:</td>
              <td style="width: 100px"><input id="txtname" style="width: 150px" type="text" name="name" maxlength="15" value="匿名" /></td>
            </tr>
          </table>
        </td>
      </tr>
      <tr>
        <td style="vertical-align: middle;" valign="middle" colspan="2">
          <div style="width: 480px; height: 300px; border-right: white thin solid; border-top: white thin solid; font-size: 10pt; border-left: white thin solid; border-bottom: white thin solid; font-family: verdana, arial; overflow:scroll; text-align: left;" id="DIV_CHAT">
          </div>
        </td>
      </tr>
      <tr>
        <td style="width: 310px">
          <input id="txtmsg" style="width: 350px" type="text" name="msg" onkeydown="return clickBtn(this)"/></td>
        <td style="width: 85px">
          <input id="Submit2" style="font-family: verdana, arial" type="button" value="发送" onclick="set_chat_msg()"/></td>
      </tr>
      <tr>
        <td colspan="1" style="font-family: verdana, arial; text-align: center; width: 350px;">
          </td>
        <td colspan="1" style="width: 85px; font-family: verdana, arial; text-align: center">
        </td>
      </tr>
    </table>
  </div>
</body>
</html>

效果图如下:

PHP+mysql+ajax轻量级聊天室实现方法详解

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
浅谈PHP与C#的值类型指向区别的详解
May 21 PHP
析构函数与php的垃圾回收机制详解
Oct 28 PHP
php通过字符串调用函数示例
Mar 02 PHP
php的dl函数用法实例
Nov 06 PHP
四个PHP非常实用的功能
Sep 29 PHP
php pthreads多线程的安装与使用
Jan 19 PHP
简单PHP会话(session)说明介绍
Aug 21 PHP
PHP模糊查询的实现方法(推荐)
Sep 06 PHP
php表单文件iframe异步上传实例讲解
Jul 26 PHP
完美解决Thinkphp3.2中插入相同数据的问题
Aug 01 PHP
PHP使用curl_multi_select解决curl_multi网页假死问题的方法
Aug 15 PHP
Laravel的加密解密与哈希实例讲解
Mar 24 PHP
php实现跨域提交form表单的方法【2种方法】
Oct 17 #PHP
php性能分析之php-fpm慢执行日志slow log用法浅析
Oct 17 #PHP
详解PHP原生DOM对象操作XML的方法
Oct 17 #PHP
php排序算法实例分析
Oct 17 #PHP
基于thinkPHP框架实现留言板的方法
Oct 17 #PHP
php并发加锁示例
Oct 17 #PHP
thinkPHP自动验证、自动添加及表单错误问题分析
Oct 17 #PHP
You might like
PHP_Flame(Version:Progress)的原代码
2006/10/09 PHP
frename PHP 灵活文件命名函数 frename
2009/09/09 PHP
PHP的文件操作与算法实现的面试题示例
2015/08/10 PHP
PHP中empty和isset对于参数结构的判断及empty()和isset()的区别
2015/11/15 PHP
Laravel实现定时任务的示例代码
2017/08/10 PHP
PHP开发中解决并发问题的几种实现方法分析
2017/11/13 PHP
php 广告点击统计代码(php+mysql)
2018/02/21 PHP
js GridView 实现自动计算操作代码
2009/03/25 Javascript
Jquery中children与find之间的区别详细解析
2013/11/29 Javascript
JQuery下拉框应用示例介绍
2014/04/23 Javascript
Javascript判断文件是否存在(客户端/服务器端)
2014/09/16 Javascript
js获取时间并实现字符串和时间戳之间的转换
2015/01/05 Javascript
jQuery实现的网页右下角tab样式在线客服效果代码
2015/10/23 Javascript
基于jquery实现页面滚动到底自动加载数据的功能
2015/12/19 Javascript
vue.js在标签属性中插入变量参数的方法
2018/03/06 Javascript
微信小程序支付前端源码
2018/08/29 Javascript
jQuery模拟html下拉多选框的原生实现方法示例
2019/05/30 jQuery
微信小程序实现轨迹回放的示例代码
2019/12/13 Javascript
JQuery+drag.js上传图片并且实现图片拖曳
2020/11/18 jQuery
[03:00]2014DOTA2国际邀请赛 Titan淘汰潸然泪下Ohaiyo专访
2014/07/15 DOTA
[00:12]DAC2018 天才少年转战三号位,他的SOLO是否仍如昔日般强大?
2018/04/06 DOTA
python 将字符串转换成字典dict
2013/03/24 Python
Python多线程、异步+多进程爬虫实现代码
2016/02/17 Python
python处理html转义字符的方法详解
2016/07/01 Python
python 删除列表里所有空格项的方法总结
2018/04/18 Python
django-filter和普通查询的例子
2019/08/12 Python
Python使用itchat模块实现简单的微信控制电脑功能示例
2019/08/26 Python
Python3 Tkinkter + SQLite实现登录和注册界面
2019/11/19 Python
pycharm 更改创建文件默认路径的操作
2020/02/15 Python
基于Python组装jmx并调用JMeter实现压力测试
2020/11/03 Python
pycharm如何设置官方中文(如何汉化)
2020/12/29 Python
奥巴马胜选演讲稿
2014/05/15 职场文书
给病人的慰问信
2015/03/23 职场文书
有趣的二维码:使用MyQR和qrcode来制作二维码
2021/05/10 Python
实现GO语言对数组切片去重
2022/04/20 Golang
Redis 报错 error:NOAUTH Authentication required
2022/05/15 Redis