所以,我正在學習如何編寫php now.I想建立一個小型購物網站。我的index.html看起來是這樣的:跳轉到我們第一次上傳頁面的PHP代碼部分
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="topnav">
<a class="active" href="#index.html">Home</a>
<a href="loginAdmin.php">Administrator</a>
<a href="loginUser.php">Register User</a>
<a href="newAccount.php">Register New Account</a>
</div>
<img class="centerImage" src="eshop.jpg">
</body>
</html>
和loginAdmin.php文件看起來像這樣:
<?php
session_start();
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
@mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input type="text" placeholder="User Name:" />
<input type="password" placeholder="Password:" />
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
如果按下loginAdmin鏈接,以便在PHP代碼的用戶將被執行,我不想這樣,只有在用戶按下登錄按鈕後,我想要執行php代碼塊。我怎樣才能做到這一點?也許我應該分開文件(PHP和HTML),而不是用戶href在index.html中的PHP文件?和index.html文件應該是index.php?
你需要給輸入名稱(例如'username'),然後檢查是否設置了$ _POST ['username']'(或$ _REQUEST,但我更喜歡精確)(比如'isset($ _ POST ['username']') - >然後執行你所需要的,否則只需要顯示錶格 – Jeff
以及通過使用會話認證用戶來完成它的正確方法。如果用戶會話存在,以顯示更多內容。 –
[Little Bobby](http://bobby-tables.com/)說*** [你的腳本存在SQL注入攻擊風險。](http://stackoverflow.com/questions/60174/how-can- ***)瞭解[MySQLi](http://php.net/manual)[準備](http://en.wikipedia.org/wiki/Prepared_statement)聲明/en/mysqli.quickstart.prepared-statements.php)。即使[轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! –