欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP+mysql+ajax輕量級聊天室實現(xiàn)方法詳解

 更新時間:2016年10月17日 12:04:05   作者:ttibm  
這篇文章主要介紹了PHP+mysql+ajax輕量級聊天室實現(xiàn)方法,結(jié)合實例形式分析了php+mysql實現(xiàn)實時聊天室功能的具體步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了PHP+mysql+ajax輕量級聊天室實現(xiàn)方法。分享給大家供大家參考,具體如下:

做了一個QQ聊天交友網(wǎng)站,想加個聊天的功能,于是做完用PHP做了簡單又強大的聊天室

1. 創(chuàng)建mysql數(shù)據(jù)庫表:

復(fù)制代碼 代碼如下:
create table chat( id bigint AUTO_INCREMENT,username varchar(20), chatdate datetime,msg varchar(500), primary key(id));

2.編寫建議連接數(shù)據(jù)庫函數(shù):

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('沒有你找到指定數(shù)據(jù)庫');
 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發(fā)送和接收函數(shù):

ajax發(fā)送函數(shù)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接收函數(shù)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='無敵戰(zhàn)神';
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聊天交友網(wǎng)站</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="發(fā)送" 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>

效果圖如下:

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP+MySQL留言板開發(fā)專題》、《PHP+ajax技巧與應(yīng)用小結(jié)》、《php文件操作總結(jié)》、《PHP運算與運算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設(shè)計有所幫助。

相關(guān)文章

  • 淺談php中fopen不能創(chuàng)建中文文件名文件的問題

    淺談php中fopen不能創(chuàng)建中文文件名文件的問題

    下面小編就為大家?guī)硪黄獪\談php中fopen不能創(chuàng)建中文文件名文件的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-02-02
  • JavaScript實現(xiàn)滾動欄效果的方法

    JavaScript實現(xiàn)滾動欄效果的方法

    這篇文章主要介紹了JavaScript實現(xiàn)滾動欄效果的方法,涉及javascript操作html元素實現(xiàn)滾動的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下
    2015-04-04
  • php 在線打包_支持子目錄

    php 在線打包_支持子目錄

    用php實現(xiàn)的在線打包的工具,并可以支持子目錄使用純php對目錄和文件進行打包壓縮,壓縮當然不能跟winrar比(壓縮比差不多相當于winrar壓縮時的最快模式)。
    2008-06-06
  • PHP日志LOG類定義與用法示例

    PHP日志LOG類定義與用法示例

    這篇文章主要介紹了PHP日志LOG類定義與用法,結(jié)合實例形式分析了日志log的具體定義及使用方法,涉及php文件讀寫、日期時間及字符串等相關(guān)操作技巧,需要的朋友可以參考下
    2018-09-09
  • php實現(xiàn)數(shù)據(jù)庫的增刪改查

    php實現(xiàn)數(shù)據(jù)庫的增刪改查

    本文給大家介紹的是PHP連接數(shù)據(jù)庫以及實現(xiàn)數(shù)據(jù)庫的增刪改查功能的方法及示例代碼,希望對大家學(xué)習(xí)php能夠有所幫助
    2017-02-02
  • php遍歷目錄輸出目錄及其下的所有文件示例

    php遍歷目錄輸出目錄及其下的所有文件示例

    好多次筆試都會遇到這個問題,本文特寫下php遍歷目錄輸出目錄及其下的所有文件的方法
    2014-01-01
  • PHP實現(xiàn)GIF圖片驗證碼

    PHP實現(xiàn)GIF圖片驗證碼

    這篇文章主要介紹了PHP如何生成GIF動態(tài)圖片驗證碼,在注冊界面時大家經(jīng)常用到驗證碼,需要了解的朋友可以參考下
    2015-11-11
  • 淺析php-fpm靜態(tài)和動態(tài)執(zhí)行方式的比較

    淺析php-fpm靜態(tài)和動態(tài)執(zhí)行方式的比較

    這篇文章主要介紹了php-fpm靜態(tài)和動態(tài)執(zhí)行方式的比較,較為詳細的分析了php-fpm靜態(tài)和動態(tài)執(zhí)行方式的原理、參數(shù)功能與相關(guān)使用技巧,需要的朋友可以參考下
    2016-11-11
  • Uncaught exception com_exception with message Failed to create COM object

    Uncaught exception com_exception with message Failed to crea

    Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `InternetExplorer.Application': 拒絕訪問
    2012-01-01
  • 在同一窗體中使用PHP來處理多個提交任務(wù)

    在同一窗體中使用PHP來處理多個提交任務(wù)

    在PHP中的處理窗體數(shù)據(jù)比其它網(wǎng)頁程序語言更簡單——如果你使用這種語言一段時間后,你會發(fā)現(xiàn)這是一個不可爭辯的事實。這種操作的簡易性使它可以容易地處理更為復(fù)雜的窗體事件,包括今天討論的主題,即在同一個窗體中通過多個按鈕來處理不同的任務(wù)。
    2008-05-05

最新評論