我有一个这样的登录表单:
<?php include "base.php"; ?>
<div id="loginpart">
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
?>
You are logged in as <b><?=$_SESSION['Username'];?> </b>. | <a href="logout.php">LogOut</a>
<?php
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM user WHERE username = '".$username."' AND user_password = '".$password."'");
if($checklogin)
{
$row = mysql_fetch_row($checklogin);
$_SESSION['Username'] = $username;
$_SESSION['LoggedIn'] = 1;
echo "<p>Success: We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
//header('Location:index.php');
}
else
{
echo "<p>Error: Sorry, your account could not be found. Please <a href='"index.php'">click here to try again</a>.</p>";
}
}
else
{
?>
<form method="post" action="index.php" name="loginform" id="loginform">
Username:<input type="text" name="username" id="username" />
Password:<input type="password" name="password" id="password" />
<input type="submit" name="login" id="login" value="Login" />
| <a href="register.php">Register</a>
</form>
<?php
}
?>
</div>
首先检查用户是否登录。如果没有,请登录。包括base.php调用数据库:
<?php
session_start();
$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "login"; // the name of the database that you are going to use for this project
$dbuser = "root"; // the username that you created, or were given, to access your database
$dbpass = ""; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
错误在检查用户名和密码的第二个括号中。
数据库表是:
create table user(
user_ID smallint unsigned auto_increment,
username varchar(30),
user_password varchar(16),
user_fname VARCHAR(30) NOT NULL,
user_lname VARCHAR(30) NOT NULL,
user_contact varchar(14),
user_email varchar(30),
user_street varchar(20),
user_city varchar(20),
constraint pk_user primary key (user_ID)
) engine innodb;
问题是,即使我输入错误的用户名或密码。它让我登录。
返回成功可能是因为没有语法错误,并且您的查询执行成功。但这并不意味着行被返回。需要检查空行
if(mysql_num_rows($checklogin) > 0)
{
$row = mysql_fetch_row($checklogin);
$_SESSION['Username'] = $username;
$_SESSION['LoggedIn'] = 1;
echo "<p>Success: We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
//header('Location:index.php');
}
else
{
echo "<p>Error: Sorry, your account could not be found. Please <a href='"index.php'">click here to try again</a>.</p>";
}
您没有检查是否返回一行。
if($checklogin)
将始终求值为true,即使结果集为空(因为密码错误或未找到用户)。
你需要用一个检查非空结果集的子句来替换这个if子句,例如:
if(mysql_num_rows($checklogin) > 0)
作为旁注:你可能还想选择更有表现力的变量名,例如$checklogin_result
和$checklogin_row
,这样如果你的项目有一天变得非常大,你就不会失去视线;)