PHP學習練手(十)
阿新 • • 發佈:2018-12-23
<?php # Script 9.3 - register.php
$page_title = 'Register';
include ('../include/header.html');
//檢查提交狀態
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
//連線資料庫
require ('../mysqli_connect.php');
$errors = array(); //儲存錯誤資訊
//檢查first name
if(empty ($_POST['first_name']))
{
$errors[] = 'You forgot to enter your first name';
}else{
$fn = mysqli_real_escape_string($mysqli, trim($_POST['first_name']));
}
//檢查last name
if (empty($_POST['last_name']))
{
$errors[] = 'You forgot to enter your last name' ;
}else{
$ln = mysqli_real_escape_string($mysqli, trim($_POST['last_name']));
}
//檢查email Address
if (empty($_POST['email']))
{
$errors[] = 'You forgot to enter your email';
}else{
$e = mysqli_real_escape_string($mysqli , trim($_POST['email']));
}
//檢查password 和 confirm password
if (!empty($_POST['pass1']))
{
if ($_POST['pass1'] != $_POST['pass2'])
{
$errors[] = 'Your password did not match the confirm password';
}else{
$p = mysqli_real_escape_string($mysqli, trim($_POST['pass1']));
}
}else{
$errors[] = 'You forgot to enter your password';
}
//檢查是否存在錯誤
if (empty($errors)) { //無誤
//執行insert操作
$sql = "INSERT INTO users(first_name, last_name, email, pass, registration_date) VALUES (
'$fn', '$ln', '$e', SHA1('$p'), NOW()
)";
$res = @mysqli_query($mysqli, $sql);
if($res) //插入成功
{
echo '<h1>Thank you!</h1>
<p>You are now registered. In Chapter 12 you will actually be able to login in!</p><p><br/></p>';
}else{ //插入失敗
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience</p>';
echo '<p>'.mysqli_error($mysqli).'<br /><br />'.$sql.'</p>';
}
mysqli_close($mysqli); //關閉資料庫
include ('../include/footer.html');
exit();
}else{ //有誤
echo '<h1>Error!</h1>
<p class="error">The following error(s) occured:<br/ >';
foreach ($errors as $msg) {
echo "- $msg<br/ >";
}
echo '</p><p>Please try again</p><p><br/ ></p>';
}
mysqli_close($mysqli); //關閉資料庫
}
?>