iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 17
3
Software Development

後端基礎PHP+Mysql & Laravel 30日養成計畫系列 第 17

Day 17 留言板實作(一):留言者註冊、登入功能

留言板是我第一個練習的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">

這段語法呈現在網頁上看起來就會是這樣
https://ithelp.ithome.com.tw/upload/images/20191004/20120024ISH3CeSMYj.png

第一筆資料的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();

}

?>

樣式模板
(由於筆者主要是學後端語言,前端的部份是自己亂寫的,還請大家鞭小力點> <)
style.html


        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 110vh;
                margin: 5;
            }

            .full-height {
                height: 70vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }
            .position-abs {
                position: absolute;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 20px;
            }
            .bottom {
                bottom: 60px;
            }
            .left {
                left: 60px;
            }
            .content{
                font-size: 28px;
                text-align: center;
            }


            .title{
                text-align: center;
                font-size: 75px;
            }
            .warning {
                text-align: center;
                font-size: 25px;
                top: 100px;
                color: #AA0000;
            }

            .success {
                text-align: center;
                font-size: 25px;
                top: 100px;
                color: #003377;
            }

            .home > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 19px;
                font-weight: 600;
                letter-spacing: .125rem;
                text-decoration: none;
                text-transform: uppercase;
            }
            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 19px;
                font-weight: 600;
                letter-spacing: .125rem;
                text-decoration: none;
            }
            .note{
                background-color: #003377;
                color: #003377;
                font-size: 25px;
                font-weight: 500;
                letter-spacing: .125rem;
                line-height: 60px;
                text-decoration: none;
                height: 0vh;
                text-align: left;
                left: 260px;
                right: 500px;
                top: 200px;
                position: absolute;
                margin: 10;
                margin-right:50px;

            }

            .m-b-md {
                margin-bottom: 40px;
            }
        </style>

要在網頁上執行php檔的話,要先cd進那個檔案目錄下,然後下這個指令:

$php -S localhost:8888

打開瀏覽器,網址輸入:http://localhost:8888/要執行的檔名.php

何時用include,何時用require?

  • 當引用檔案不存在時,require 會產生錯誤訊息並停止程式執行。而 include 會顯示警告訊息,但是程式會繼續往下執行。
  • 在 include 載入檔案執行時,文件每次都要進行讀取與評估;而對於 require 來說,文件只處理一次。也就是說引入檔的程式碼使用率較高的,建議使用 require方法。若是在迴圈或是判斷式中引入檔案,建議使用 include 方法。若引用的檔案很重要,也建議使用 require 的方法,因為讀取檔案錯誤的同時,程式也會停止,避免更多錯誤產生。
  • include 能回傳值,require 則不行。

上一篇
Day 16 Git入門教學:將檔案加入版本控制系統下
下一篇
Day 18 留言板實作(二):寫下留言及查看所有留言功能
系列文
後端基礎PHP+Mysql & Laravel 30日養成計畫36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

我要留言

立即登入留言