功能:
前端页面获取用户姓名 和 发布的内容并加载到数据库中 然后提取数据库的数据显示在前端页面
效果图:
方法解析:
一.表单获取用户数据 login.php 和 main.php
1.login.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
请输入您的昵称<br>
<form action="main.php" method="post" target="_self">
<input type="text" name="name" cols="20">
<input type="submit" value="登录">
</form>
</body>
<?php
2.main.php(布局设置)
<?php
session_start();
$_SESSION['name']=$_POST['name'];
?>
<html>
<frameset rows="80%,20%">
<frame src="chatDisplay.php" name="chatDisplay">
<frame src="speak.php" name="speak">
</frameset>
</html>
二.加载用户信息到数据库中
1.speak.php(用来发布内容)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发言</title>
</head>
<body>
<form action="Contents.php" method="post" target="_self">
<input type="text" name="contents">
<input type="submit" value="发言">
</form>
</body>
</html>
2.Contents.php
插入数据时要确保数据类型 和 相应的排序规则(注意编码转成utf-8_general_ci)要对应
<?php
session_start();
if($_POST['contents']) {
date_default_timezone_set('PRC');
$hostname = 'localhost';
$username = 'root';
$psd = '';
$link = mysqli_connect($hostname, $username, $psd, 'test');
if(!$link){echo "连接失败!";}
mysqli_query($link, 'set names utf8');
$time=date("Y-m-d H:i:s",time());
$name = $_SESSION['name'];
$words=$_POST['contents'];
$sql = "insert into test.chatroom(name, words, reg_date) values ('$name','$words','$time');";
$result=mysqli_query($link,$sql);
if ($result) {
echo "添加记录成功!";
} else {
echo "添加记录失败!";
}
}
else{
echo "获取数据失败!";
}
?>
三.数据的提取
1.http-equiv="refresh"content="5;url=chatDisplay.php"> 设置每5s更新一次页面
2.mysql_data_result($result,$n)获取n条数据 并返回给result
3.list()=mysqli_fetch_array()//提取每一行数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="5;url=chatDisplay.php">
<title>发言</title>
</head>
<body>
<?php
$hostname='localhost';
$username='root';
$psd='';
$link=mysqli_connect($hostname,$username,$psd,'test');
mysqli_query($link,'set names utf8');
$sql="select * from test.chatRoom order by user_id";
$result=$link->query($sql);
$rows=mysqli_num_rows($result);
mysqli_data_seek($result,$rows);
if($rows<15)
{
$l=$rows;
}
else{
$l=15;
}
for($i=1; $i<=$l; $i++)//输出这15条信息
{
list($id,$name,$words,$reg_date)=mysqli_fetch_array($result);
echo $reg_date;
echo " ".$name."说: ";
echo $words;
echo "<br>";
}
?>
</body>