技术开发 频道

基于PHP MySQL的聊天室设计

  2 、代码设计

  以上规划完成后,就可以着手代码设计了,采用php可以非常简明实现以上的功能。

  2.1 用户登录login.php,本段代码是一个完全HTML网页

 

<html>
<head>
<title>用户登录</title>
</head>
<body>请输入您的昵称<br>
<form action="main.php" method="post" target="_self">
<input type="text" name="nick" cols="20">
<input type="submit" value="登录">
</body>
</html>

  用户提交自己的昵称后,就进入到聊天室,以下的处理交由main.php处理。

  2.2 页框主体代码段main.php:

 

<?
setcookie(
"nick",$nick) //用cookie记录用户昵称,是常用的传递变量方法
?
>
<html>
<title>山西铝厂聊天室试用版ver1.0</title>
<frameset rows="80%,*">
<frame src=" cdisplay.php" name="chatdisplay">
<frame src="speak.php" name="speak">
</frameset>
</html>

 

  2.3 显示发言cdisplay.php

  本代码段的任务是将表chat中的数据取出,显示在页框中。每次刷新时,取数据库中最近的15条发言。同时,为防止数据库无限增大,需设计删除陈旧数据的功能。代码如下

 

<html>
<head>
<title>显示用户发言</title>
<meta http-equiv="refresh" content="5;url=cdisplay.php">
</head>
<body>
<?
$link_ID
=mysql_connect("main","root");
//链接Mysql服务器 服务器名为main,管理员名为root
mysql_select_db(
"abc"); //选择数据库
$str
="select * from chat ORDER BY chtime;" ; //查询字符串
$result
=mysql_query($str, $link_ID); //送出查询
$rows
=mysql_num_rows($result); //取得查询结果的记录笔数
//取得最后15笔发言,并显示
@mysql_data_seek($resut,$rows
-15); //移动记录指针到前15笔记录
if ($rows<15) $l=$rows; else $l=15; //记录总数小于15,则最多为该记录数
for ($i=1;$i<=$l;$i ) {
list($chtime,$nick,$words)
=mysql_fetch_row($result);
echo $chtime; echo
" ";echo $nick; echo":" ; echo $words; echo "<BR>";
}
//清除库中过时的数据
@mysql_data_seek($result,$rows
-20); //移动记录指针到前20笔记录
list($limtime)
=mysql_fetch_row($result);
$str
="DELETE FROM chat WHERE chtime<'$limtime' ;" ;
$result
=mysql_query($str,$link_ID); //送出查询字符串,库中只留前20个记录
mysql_close($link_ID);
?
>
</body>
</html>

  2.4 送出发言到数据库speak.php

 

<html>
<head>
<title>发言</title>
</head>
<body>
<?
If ($words)
{ $link_ID
=mysql_connect("main","root");
mysql_select_db(
"abc"); //数据库名为abc
$
time=date(y).date(m).date(d).date(h).date(i).(date(s); //取得当前时间
$str
="INSERT INTO chat(chtime,nick,words) values
('$time','$nick','$words');" ;
mysql_query($str,$link_ID); //送出发言到数据库
mysql_close($link_ID);
}
?
>
//输入发言的表单
<form action="speak.php" method="post" target=" _self">
<input type="text" name="words" cols="20">
<input type="submit" value="发言">
</form>
</body>
</html>

   完成以上工作后,一个简单的聊天室制作就完成了。当然,设计者可以根据个人爱好做一些个性化设计,如增加一个页框,显示当前聊天室人员名单、增加发言表情、取得发言者IP、进一步美化页面等等。

0
相关文章