表白墙主要功能包括:发布以及评论。
数据库结构
数据表love
数据表comment
首页
公共函数文件 tool.php
<?php
function get($name){
return isset($_GET)?$_GET['id']:"";
}
function post($name){
return isset($_POST)?$_POST['content']:"";
}
function conn(){
//数据库驱动类型:host=主机名;dbname=数据库
$dns = "mysql:host=localhost;dbname=noxue";
//连接字符串,账号,密码
return new PDO($dns,"root","root");
}
首页 index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表白墙</title>
<style type="text/css">
.item{
background: #dddddd;
margin: 20px;
}
.item p+p{
color: #999999;
}
</style>
</head>
<body>
<a href="./love.html">假装发一个表白</a>
<?php
require_once "./tool.php";
$db=conn();
$sql='select * from love';
$res = $db->query($sql);
foreach ($res as $row){
?>
<div class="item">
<p><?php
echo substr($row['content'],0,20);
echo "...<a href='./content.php?id=".$row['id']."'>详细内容</a>"?></p>
<p><?=$row['created_at']; ?></p>
</div>
<?php
}
?>
</body>
</html>
发表功能
love.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发布表白</title>
</head>
<body>
<form action="love.php" method="post">
<p>
<textarea name="content" id="" cols="30" rows="10" placeholder="请输入表白信息"></textarea>
</p>
<p>
<input type="submit" value="发布表白">
</p>
</form>
</body>
</html>
love.php
<?php
require_once "./tool.php";
//获取数据库连接
$content = post('content');
$sql = 'insert into love(content) VALUES("'.$content.'")';
echo $sql;
$db=conn();
//执行查询操作
$count=$db->exec($sql);
echo $count;
$db=null;
//跳转到首页
header('Location: index.php');
详细内容
content.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表白内容</title>
<style type="text/css">
</style>
</head>
<body>
<?php
require_once './tool.php';
$id=get('id');
$db=conn();
$sql = 'select * from love WHERE id='.$id;
$res = $db->query($sql);
$love=null;
foreach($res as $row){
$love=$row;
break;
}
//print_r($love);
?>
<div class="content">
<p><?=$love['created_at']?></p>
<p><?=$love['content']?></p>
</div>
<form action="comment.php" method="post">
<input type="hidden"name="id" value="<?=$love['id']?>">
<p><textarea name="content" id="" cols="30" rows="10"></textarea></p>
<p><input type="submit" value="发布评论"></p>
</form>
<?php
$sql='select * from comment WHERE love_id='.$id;
$res= $db->query($sql);
foreach($res as $row){
?>
<div class="comment-item">
<p><?=$row['created_at']?></p>
<p><?=$row['content']?></p>
</div>
<?php
}
?>
</body>
</html>
发表评论功能
comment.php
<?php
require_once 'tool.php';
$id = isset($_POST)?$_POST['id']:"";
$content = post('content');
$sql = 'insert into comment(love_id,content,created_at) VALUES ('.$id.',"'.$content.'",now())';
echo $sql;
$db = conn();
$count=$db->exec($sql);
header("Location: content.php?id=".$id);