如何使用PHP實現一個簡單的線上預訂系統
引言:
隨著網路的發展,線上預訂系統已經成為許多行業的標配。本文將介紹如何使用PHP語言來實作一個簡單的線上預訂系統,並給出對應的程式碼範例。
一、系統需求分析
我們的線上預訂系統需要具備以下基本功能:
二、資料庫設計
在MySQL中建立兩個表,一個是用來儲存使用者資訊的user表,另一個是用來儲存飯店資訊的hotel表。使用者資訊表的架構如下:
CREATE TABLE user
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(50) NOT NULL,
email
varchar(50) NOT NULL,
password
varchar(50) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
飯店資訊表的結構如下:
#CREATE TABLE hotel
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(50) NOT NULL,
address
varchar(100) NOT NULL,
price
decimal(10,2) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
三、系統實作
程式碼範例:
register.php:
<?php require 'db.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; $email = $_POST['email']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $sql = "INSERT INTO user(name, email, password) VALUES('$name', '$email', '$password')"; mysqli_query($conn, $sql); header('Location: login.php'); exit; } ?> <form action="" method="post"> <input type="text" name="name" placeholder="用户名" required> <input type="email" name="email" placeholder="邮箱" required> <input type="password" name="password" placeholder="密码" required> <button type="submit">注册</button> </form>
login.php:
<?php require 'db.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $email = $_POST['email']; $password = $_POST['password']; $sql = "SELECT * FROM user WHERE email='$email'"; $result = mysqli_query($conn, $sql); $user = mysqli_fetch_assoc($result); if ($user && password_verify($password, $user['password'])) { session_start(); $_SESSION['user_id'] = $user['id']; header('Location: index.php'); exit; } else { echo '用户名或密码错误'; } } ?> <form action="" method="post"> <input type="email" name="email" placeholder="邮箱" required> <input type="password" name="password" placeholder="密码" required> <button type="submit">登录</button> </form>
程式碼範例:
##index.php:<?php require 'db.php'; $sql = "SELECT * FROM hotel"; $result = mysqli_query($conn, $sql); $hotels = mysqli_fetch_all($result, MYSQLI_ASSOC); ?> <?php foreach($hotels as $hotel): ?> <h3><?php echo $hotel['name']; ?></h3> <p>地址:<?php echo $hotel['address']; ?></p> <p>价格:<?php echo $hotel['price']; ?></p> <a href="booking.php?id=<?php echo $hotel['id']; ?>">预订</a> <?php endforeach; ?> booking.php: <?php session_start(); require 'db.php'; if (!isset($_SESSION['user_id'])) { header('Location: login.php'); exit; } $hotel_id = $_GET['id']; $user_id = $_SESSION['user_id']; $sql = "INSERT INTO booking(user_id, hotel_id) VALUES('$user_id', '$hotel_id')"; mysqli_query($conn, $sql); echo '预订成功'; ?>
以上是如何使用PHP實現一個簡單的線上預訂系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!