欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-04-02 12:02:52
本文实例讲述了php+mysql+ajax轻量级聊天室实现方法。分享给大家供大家参考,具体如下: 做了一个qq聊天交友网站,想加个聊天的功能,于是做完用php做了简单又强...

本文实例讲述了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+mysql留言板开发专题》、《php+ajax技巧与应用小结》、《php文件操作总结》、《php运算与运算符用法总结》、《php网络编程技巧总结》、《php基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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