编写一个在线留言本,实现用户的在线留言功能,留言信息存储到数据库,要求数据表内容以及使用PHP编码完成

数据表设计

  • 分析数据表结构 留言信息:id,标题,内容,时间,留言人
  • 数据表的创建:留言本表:message
creat table message(
 'id' int unsigned not null auto_increment primary key,
 'title' varchar(200) not null default '',
 'content' varchart(300) not null default '',
 'creat_time' int not null default '0',
 'user_name' varchar(30) unsigned not null default '',
  key message_user_name(user_name)
)engine=InnoDb default charset=utf8;

选择连接数据库的方式

  • PDO:可扩展性更好,支持 预处理,面向对象
  • mysqli:支持支MySQL操作,支持预处理,效率比PDO高
  • PDO基本操作
$pdo = new PDO($dsn,$username,$password,$attr);
$sql = 'select id,title,content from message where user_name = :user_name';
$ject = $pdo -> prepare($sql);
$ject -> execut([':user_name' => $user_name]);
$result = $ject -> fetchALL(PDO::FETCH_ASSOC);

创建form表单

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>留言本</title>
</head>
<body>
    <form action="store.php" method="post">
        标题: <input type="text" name="title">
        内容: <input type="text" name="content">
        留言人: <input type="text" name="user_name">
        <input type="submit" vakue="添加">
    </form>
</body>
</html>

store.php

// 标题
	$title = $_POST['title'];
	// 内容
	$content = $_POST['content'];
	// 留言人
	$user_name = $_POST['user_name'];
	
	if (empty($title) || empty($content) || empty($user_name)) {
		exit('数据不能为空');
	}
	
	try {
		// 配置
		$dsn = 'mysql:dbname=test;host=localhost';
		// 用户名
		$username = 'test';
		// 密码
		$password = 'test';
		//竖向
		$attr = [
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
		];
		// 链接PDO
		$pdo = new PDO($dsn, $username, $password, $attr);
		// 编写sql语句
		$sql = 'insert into message (title, content, user_name, creat_time) values (:title, :content, :user_name, :creat_time)';
		// 预处理
		$stmt = $pdo->prepare($sql);
		$data = [
			':$title'     => $title,
			':content'    => $content,
			':user_name'  => $user_name,
			':creat_time' => time(),
		];
		$stmt->execute($data);
		$row = $stmt->rowCount();
		
		if ($row) {
			echo '添加成功';
		} else {
			echo '添加失败';
		}
	} catch (PDOException $exception) {
		// 异常
		echo $exception->getMessage();
	}

例:设计一个无线分类表

id title pid 1 服装 0 2 上衣 1 3 长袖 2

id title pid path 1 服装 0 0-1 2 上衣 1 0-1-2 3 长袖 2 0-1-2-3