PHP程序功能設計

以留言板爲例。php

數據表設計html

  分析數據表結構:有哪些信息須要存儲:留言信息:ID,留言標題,留言內容,留言時間,留言人mysql

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鏈接數據庫的方式sql

  PDO:可擴展性更好,支持預處理,面向對象數據庫

  MySQLi:只支持MySQL操做,支持預處理,面向對象和過程,效率較高post

  mysql:只支持MySQL數據庫,沒有預處理的支持,面向過程fetch

  PDO的基本操做:spa

<?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.htmlcode

<!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排序

相關文章
相關標籤/搜索