2014-07-22 88 views
0

我试图在php中建立一个与mysql数据库连接的登录页面。下面是登录页面的html代码,其中输入了值,然后定向到第二个在那里他们被检查PHP的页面..

<html> 
<head> 
    <title>Library Login</title> 
    <link rel="stylesheet" type="text/css" href="css/reset.css"> 
    <link rel="stylesheet" type="text/css" href="css/structure.css"> 
</head> 
<body> 
    <form class="box login" method="GET" action="http://localhost/redirect.php"> 
     <label align="center"><font size="6" color="grey">Library System</font></label> 
     <fieldset class="boxBody"> 
     <label>Username</label> 
     <input type="text" placeholder="Username" required name="username"> 
     <label><a href="#" class="rLink" tabindex="5" ></a>Password</label> 
     <input type="password" placeholder="Password" required name="password"> 
     <input type="submit" class="btnLogin" value="Login" name="login"> 
     <input type="reset" class="btnLogin" value="Reset" name="reset" > 
     <label> 
    </form> 
</html> 
</div> 

及以下就是只执行else条件的任何条目输入第二个页面的代码...我是新来的PHP和MySQL ......请大家帮帮我out ...

<?php 
$con=mysqli_connect("localhost","root","","project"); 

if(mysqli_connect_errno()) 
{ 
    echo "failed".mysqli_connect_errno(); 
} 

$uid=$_GET['username']; 
$pass=$_GET['password']; 
$sql="SELECT *FROM login"; 
$result=mysqli_query($con,$sql); 

while($data=mysqli_fetch_array($result)) 
{ 
    if($uid==$data['user'] and $pass==$data['pass']) 
    { 
     header('location:http://localhost/error/index.html'); 
    } 
    else 
    { 
     header('location:http://localhost/mam.html'); 
    } 
} 

mysqli_close($con); 
?> 
+0

没有..每次其他条件执行时检查值,而不管我输入了正确的输入或不是 – beginner

+0

我知道这不是一个答案,但你真的应该尝试移动到[PDO](http:///php.net/manual/en/book.pdo.php)而不是mysqli。 – pid

+1

如果结果的第一行不匹配,那么您将在else部分中并且使用header()调用您将离开mam.html并且不回到此脚本。您应该使用WHERE子句来获取相关的行(如果存在)。而且,在将输入值放入WHERE子句之前,应先阅读有关占位符的准备语句。 – VMai

回答

0

好吧,在您处理身份验证时,让我们稍微改进您的代码。

<?php 

// Do not connect using root, especially when not setting a password: 
$con=mysqli_connect("localhost","projectuser","password","project"); 
if(mysqli_connect_errno()) 
{ 
echo "failed".mysqli_connect_errno(); 
} 

$uid = $_GET['username']; 
$pass = $_GET['password']; 

// This is the main problem, there was a typo: 
$sql = "SELECT * FROM login"; 

// Directly ask the DB if the credentials are correct. 
// Then you do not need the loop below. 
// BUT: Do not forget to escape the data in this case! 
$sql .= " WHERE uid = '" . mysqli_real_escape_string($uid) . "' AND pass = '" . mysqli_real_escape_string($pass) . "'"; 

$result=mysqli_query($con,$sql); 
if ($result->num_rows === 1) { 
    header('location:http://localhost/mam.html'); 
} else { 
    header('location:http://localhost/error/index.html'); 
} 
mysqli_close($con); 
?> 

进一步的改进是散列(和盐)数据库中的密码。

另外,正如VMai指出的那样,使用准备好的陈述将是适当的。

+1

'mysql_real_escape_string'这是一个'mysql_'函数;小心;-) –

+0

你在混合mysqli_ *函数(由OP使用)和mysql_ *函数。这是行不通的。请使用预处理语句和占位符来改进mysqli行中的代码,并将输入绑定到占位符而不是字符串连接。 – VMai

+0

错过了我,修正了这个问题。但是,如果两个模块都可用 - 这至少可以用于逃跑。 – brainbowler