1. 先建立一個”admin”資料庫,並建立” manager”資料表,資料表中新增三欄位分別為「idno」”(主索引)、「 id」 char(12)、「pwd」 char(12)。
2. 在config.php內設定資料庫環境。
<?php //======資料庫變數======// $cfgDB_HOST = 'localhost'; //資料庫所在主機位置 $cfgDB_PORT ="3306"; //資料庫PORT(預設為3306) $cfgDB_USERNAME ="hebe"; //資料庫帳號 $cfgDB_PASSWORD ="12345"; //資料庫密碼 $cfgDB_NAME = "admin"; //使用的資料庫 ?>
3. connect.php插入config.php用來連結資料庫,並下選擇資料庫的指令。
<?php
// 建立資料庫連線
function create_connection()
{
include 'config.php';
$link = mysql_connect($cfgDB_HOST . ":" . $cfgDB_PORT, $cfgDB_USERNAME, $cfgDB_PASSWORD);
return $link;
}
// 選擇資料庫
function execute_sql($cfgDB_NAME, $sql, $link)
{
mysql_select_db($cfgDB_NAME, $link);
$result = mysql_query($sql, $link);
return $result;
}
?>
4. login.php為使用介面,以post方式送出。
(該範例使用Boostrap美化,使用過程可參考: Asp.net 的基本使用)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
</head>
<body>
<div class="span4" >
<form action="check.php" method="post" >
<table class="table table-bordered" >
<tr>
<th colspan="2">管理者登入</th>
</tr>
<tr>
<td> 帳 號 </td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td> 密 碼 </td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登入" class="btn btn-primary"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
5. check.php將login.php傳來兩欄位”id”及” pwd”值加以判斷帳密是否正確,若登入成功會以session方式暫存帳號並顯示於畫面中。
<?php
//連結資料庫
session_start();
require_once("connect.php");
$link = create_connection();
$id = $_POST["id"]; //login.php傳來帳號欄位輸入值
$pwd = $_POST["pwd"]; //login.php傳來密碼欄位輸入值
$sql = "select id from manager where id='$id' and pwd='$pwd'";
$rs = execute_sql("admin", $sql, $link);
$total= mysql_num_rows($rs);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
</head>
<body>
<div class="span4" >
<?php
//判斷所選取資料的數目是否大於0,若大於0則表示資料庫有這筆帳號和密碼,即登入成功
if($total>0){
$_SESSION['username'] = $id;
echo "歡迎" . $_SESSION['username'] . "登入成功!<br/>";
echo '<a class="btn btn-danger btn-small" href="logout.php">登出</a>';
}
else{
echo "帳號或密碼輸入有誤,請再重試一次!<br/>";
echo '<a class="btn btn-info btn-small" href="logout.php">返回</a>';
}
?>
</div>
</body>
</html>
6. logout.php登出,清除session值。
<?php session_start(); ?> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php //將session清空 unset($_SESSION['username']); echo '登出中......'; echo '<meta http-equiv=REFRESH CONTENT=1;url=login.php>'; ?>
完成圖
回 PHP 目錄
回首頁
好文章~~~
回覆刪除