留言板是我第一個練習的PHP+MySQL實做作品,運作概念就是讓留言者送出資料到伺服器,存進資料庫,檢視所有留言在從資料庫撈資料顯示在頁面上。
不過在這之前要先稍微介紹一下Form表單。
HTML的Form表單是用來收集使用者各種不同類型的input的,有三個主要的元素:method、action和data。
Method是指提交表單的HTTP方法,有GET和POST兩種。
GET:GET傳送的資料會被帶在網址上,因此安全性較低。
使用時機是當資料提交是被動的(如搜尋引擎查詢資料),且沒有敏感資訊時(如密碼)。
POST:POST的安全性比GET高,因為它所傳送的資料是不會被帶在網址上的。
如果要更新資料,或者資料包含敏感資訊(如密碼)時使用POST。
Action是用來定義提交資料的『 動作 』,簡單來說就是這些要提交的資料要送去哪。
Data顧名思義就是提交的資料內容,每筆資料都是一組key和value的對應。
範例:
<form name="signup" action="signup.php" method="post">
    <p>Username : <input type=text name="name"></p>
    <p>Password : <input type=password name="password"></p>
    <p><input type="submit" name="submit" value="Sign up">
這段語法呈現在網頁上看起來就會是這樣
第一筆資料的key是'name',value是輸入的使用者名稱,
第二筆資料的key是'password',value是輸入的使用者密碼。
當使用者填完名稱和密碼並按下Sign up後,便會送出資料到sign.php。
由於method是post,因此資料會存在 $_POST 這個陣列裡。
我們來看看這筆資料長怎樣
var_dump($_POST):
array(3) { ["name"]=> string(5) "Kelly" ["password"]=> string(4) "0000" ["submit"]=> string(7) "Sign up" }
接下來的留言板實做,都是使用類似這樣的form表單來完成註冊、登入及留言。
實做留言板的第一步,先去MySQL建立database與table:
mysql> create database board;
使用board這個database:
mysql> use board;
建立儲存使用者帳號密碼的table:
mysql> create table user(id int auto_increment primary key, name char(20), password char(15));
建立儲存留言的table:
mysql> create table guestbook(no int auto_increment primary key, name char(20), subject char(50), content text(500), time datetime);
接下來就要開始寫程式了:
連接資料庫的程式分開寫成一支。
db.php:
<?php
$db = mysqli_connect("localhost", "換成你的使用者名稱", "換成你的密碼", "board") or die(mysqli_error());
註冊帳號
register.php
<title>Sign up</title>
<?php
include 'style.html';
?>
<body>
     <div class="flex-center position-ref full-height">
                <div class="top-right home">
                        <a href="view.php?name="$_GET['name']"">View</a>
                        <a href="index.php">Login</a>
                        <a href="signup.php">Register</a>
                </div>
      <div class="content">
                <div class="m-b-md">
                    <form name="signup" action="signup.php" method="post">
                        <p>Username : <input type=text name="name"></p>
                        <p>Password : <input type=password name="password"></p>
                        <p><input type="submit" name="submit" value="Sign up">
                    <style>
                        input {padding:5px 15px; background:#ccc; border:0 none;
                        cursor:pointer;
                        -webkit-border-radius: 5px;
                        border-radius: 5px; }
                    </style>
                        <input type="reset" name="Reset" value="Reset">
                    <style>
                        input {
                            padding:5px 15px;
                            background:#FFCCCC;
                            border:0 none;
                            cursor:pointer;
                            -webkit-border-radius: 5px;
                            border-radius: 5px;
                            font-family: 'Nunito', sans-serif;
                            font-size: 19px;
                        }
                    </style>
                    </form>
                </div>
</body>
</html>
<!--留言者按下Signup後接著會執行以下程式碼-->
<?php
header("Content-Type: text/html; charset=utf8");
if (isset($_POST['submit'])) { 
	include 'db.php';
	$name = $_POST['name'];
	$password = $_POST['password'];
	if ($name && $password) {
		$sql = "select * from user where username = '$name'";
		$result = mysqli_query($db, $sql);
		$rows = mysqli_num_rows($result);
		if (!$rows) { //若這個username還未被使用過
			$sql = "insert user(id,username,password) values (null,'$name','$password')";
			mysqli_query($db, $sql);
			if (!$result) {
				die('Error: ' . mysqli_error());
			} else {
				echo '<div class="success">Sign up successfully !</div>';
				echo "
                    <script>
                    setTimeout(function(){window.location.href='view.php?name=" . $name . "';},2000);
                    </script>";
			}
		} else { //這個username已被使用
			echo '<div class="warning">The Username has already been used !</div>';
			echo "
                <script>
                setTimeout(function(){window.location.href='signup.php';},1000);
                </script>";
		}
	} else {
		echo '<div class="warning">Incompleted form! </div>';
        //以下為javascript語法,註冊成功後會自動跳轉到登入頁面
		echo "
<script>
setTimeout(function(){window.location.href='login.php';},2000);
</script>";
	}
}
mysqli_close($db);
?>
登入
index.php
<title>Login</title>
<?php
include 'style.html';
?>
<body>
     <div class="flex-center position-ref full-height">
                <div class="top-right home">
                        <a href="view.php?name="$_GET['name']"">View</a>
                        <a href="index.php">Login</a>
                        <a href="signup.php">Register</a>
                </div>
      <div class="content">
                <div class="m-b-md">
                    <form name="login" action="index.php" method="post">
                        <p>Username : <input type=text name="name"></p>
                        <p>Password : <input type=password name="password"></p>
                        <p><input type="submit" name="submit" value="Log in">
                    <style>
                        input {padding:5px 15px; background:#ccc; border:0 none;
                        cursor:pointer;
                        -webkit-border-radius: 5px;
                        border-radius: 5px; }
                    </style>
                        <input type="reset" name="Reset" value="Reset">
                    <style>
                        input {
                            padding:5px 15px;
                            background:#FFCCCC;
                            border:0 none;f
                            cursor:pointer;
                            -webkit-border-radius: 5px;
                            border-radius: 5px;
                            font-family: 'Nunito', sans-serif;
                            font-size: 19px;
                        }
                    </style>
                    </form>
                </div>
</body>
</html>
<?php
header("Content-Type: text/html; charset=utf8");
if (isset($_POST['submit'])) {
	include 'db.php';
	$name = $_POST['name'];
	$password = $_POST['password'];
	if ($name && $password) {
		$sql = "select * from user where username = '$name' and password='$password'";
		$result = mysqli_query($db, $sql);
		$rows = mysqli_num_rows($result);
		if ($rows) {
			echo '<div class="sucess">welcome! </div>';
			echo "
			<script>
			setTimeout(function(){window.location.href='view.php?name=" . $name . "';},600);
			</script>";
			exit;
		} else {
			echo '<div class="warning">Wrong Username or Password!</div>';
		}
	} else {
		echo '<div class="warning">Incompleted form! </div>';
		echo "
<script>
setTimeout(function(){window.location.href='login.php';},2000);
</script>";
	}
	mysqli_close();
}
?>
要在網頁上執行php檔的話,要先cd進那個檔案目錄下,然後下這個指令:
$php -S localhost:8888
打開瀏覽器,網址輸入:http://localhost:8888/要執行的檔名.php