> 백엔드 개발 > PHP 튜토리얼 > PHP+mysql+ajax로 경량 채팅방을 구현하는 방법

PHP+mysql+ajax로 경량 채팅방을 구현하는 방법

墨辰丷
풀어 주다: 2023-03-28 18:00:01
원래의
2217명이 탐색했습니다.

본 글에서는 주로 PHP+mysql+ajax 경량 채팅방 구현 방법을 소개하고, 실시간 채팅방 기능을 구현하기 위한 php+mysql의 구체적인 단계와 관련 구현 기술을 분석하여 필요한 친구들을 위한 예시를 제공합니다. 참고하시면 됩니다

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<?php

function db_connect()

{

 date_default_timezone_set("Asia/Shanghai");

 $link = mysql_connect("xxx.xxx.xxx.xxx", "databasename", "password")

      or die(&#39;无法连接: &#39; . mysql_error());

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

 return true;

}

function quote($strText)

{

  $Mstr = addslashes($strText);

  return "&#39;" . $Mstr . "&#39;";

}

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?php

   require_once(&#39;dbconnect.php&#39;);

   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(&#39;Query failed: &#39; . mysql_error());

    exit();

   }

?>

로그인 후 복사

ajax 수신 함수 chat_recv_ajax.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?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(&#39;dbconnect.php&#39;);

   db_connect();

   $sql = "SELECT *, date_format(chatdate,&#39;%Y年%m月%d日 %r&#39;) 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(&#39;Query failed: &#39; . mysql_error());

   // Update Row Information

   $msg="<table border=&#39;0&#39; style=&#39;font-size: 10pt; color: white; font-family: verdana, arial;&#39;>";

   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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

<!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("p_CHAT") != null)

    {

      document.getElementById("p_CHAT").innerHTML = oxmlHttp.responseText;

      oxmlHttp = null;

    }

    var scrollp = document.getElementById("p_CHAT");

    scrollp.scrollTop = scrollp.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(&#39;txtname&#39;).value=&#39;无敌战神&#39;;

if(i==1)document.getElementById(&#39;txtname&#39;).value=&#39;令狐冲&#39;;

if(i==2)document.getElementById(&#39;txtname&#39;).value=&#39;西门吹雪&#39;;

if(i==3)document.getElementById(&#39;txtname&#39;).value=&#39;超级玛丽&#39;;

if(i==4)document.getElementById(&#39;txtname&#39;).value=&#39;奥巴马&#39;;

if(i==5)document.getElementById(&#39;txtname&#39;).value=&#39;恐怖分子&#39;;

if(i==6)document.getElementById(&#39;txtname&#39;).value=&#39;聊斋奇女子&#39;;

if(i==7)document.getElementById(&#39;txtname&#39;).value=&#39;天朝?潘?;

if(i==8)document.getElementById(&#39;txtname&#39;).value=&#39;中500万了&#39;;

if(i==9)document.getElementById(&#39;txtname&#39;).value=&#39;神级奇葩&#39;;

if(i==10)document.getElementById(&#39;txtname&#39;).value=&#39;爱你不是两三天&#39;;

}

</script>

</head>

<body onload="SetTxtName();">

  <p style="border-right: black thin solid; border-top: black thin solid;

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

    background:#fff url(&#39;http://www.ihaonet.com/chat/blue.jpg&#39;) 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">

          <p 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="p_CHAT">

          </p>

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

  </p>

</body>

</html>

로그인 후 복사

번역은 다음과 같습니다.

요약: 위 내용은 이 글의 전체 내용입니다. 도움이 되길 바랍니다. 모두의 공부에.

관련 권장 사항:

PHP가 우회 비활성화 기능을 통해 시스템 명령을 실행하는 방법

PHP의 이메일 주소

php "{}" 중괄호 사용 요약

위 내용은 PHP+mysql+ajax로 경량 채팅방을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿