PHP程序功能设计
以留言板为例。
数据表设计
分析数据表结构:有哪些信息需要存储:留言信息:ID,留言标题,留言内容,留言时间,留言人
CREATE TABLE message( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, title VARCHAR(120) NOT NULL DEFAULT '', content VARCHAR(255) NOT NULL DEFAULT '', created_at INT UNSIGNED NOT NULL DEFAULT '0', user_name VARCHAR(32) NOT NULL DEFAULT '', KEY message_user_name(user_name) )ENGINE=InnoDB DEFAULT CHARSET=utf8;
选择PHP连接数据库的方式
PDO:可扩展性更好,支持预处理,面向对象
MySQLi:只支持MySQL操作,支持预处理,面向对象和过程,效率较高
mysql:只支持MySQL数据库,没有预处理的支持,面向过程
PDO的基本操作:
<?php try{ 操作数据库代码 }catch(PDOException $e){ echo $e->getMessage(); }
操作数据库代码:
$pdo = new PDO($dsn, $username, $password, $attr); $sql = 'SELECT id, title, content FROM message where user_name=:user_name'; $stmt = $pdo->prepare($sql); $stmt->execute([ ':user_name' => $user_name]); $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
form.html
<!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"><br> 内容:<textarea cols="35" rows="10" name="content"></textarea><br> 留言人:<input type="text" name="user_name"><br> <input type="submit" value="添加"> </form> </body> </html>
store.php
<?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=blog;host=localhost'; $username = 'root'; $password = 'rootroot'; $attr = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; $pdo = new PDO($dsn, $username, $password, $attr); $sql = 'insert into message(title, content, created_at, user_name) values(:title, :content, :created_at, :user_name)'; $stmt = $pdo->prepare($sql); $data = [ ':title' => $title, ':content' => $content, ':created_at' => time(), ':user_name' => $user_name ]; $stmt->execute($data); $rows = $stmt->rowCount(); if($rows){ exit('添加成功'); }else{ exit('添加失败'); } }catch (PDOException $e){ echo $e->getMessage(); }
无限分类表:1. id title pid/path order by排序