我有一个LOGIN PAGE,在我的数据库中有一个表,其成员包括ID,PASSWORD,USER_TYPE。 我想要我的登录页面,当用户输入他们的ID和密码时,根据他们是谁来访问网站。 (如果他们是学生去学生的页面)(如果他们是组织者,请访问组织者的页面)。
我无法通过以下编码获得结果:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$user="admin";
$pass="neehahs";
$host="localhost";
$db="login";
$con=mysqli_connect($host,$user,$pass,$db);
if(mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=($_POST['username']);
$password=md5($_POST['password']);
$username = mysqli_real_escape_string($con,$username);
$password = mysqli_real_escape_string($con,$password);
$sql="SELECT * FROM members WHERE student_id='%$username%' AND student_pass='%$password%'";
$sqldata=mysqli_query($con,$sql)
or die ("error");
while ($row=mysqli_fetch_array($sqldata)){
if($row["user_type"]=='student'){
header('location: http://localhost/greenstudio/index.html');
}
elseif
($row["user_type"]=='organizer'){
header('location: http://localhost/greenstudio/index2.html');
}else {
echo"Sorry, your credentials are not valid, Please try again.";
}
}
exit();
}
?>
答案 0 :(得分:0)
你应该有一个类似于:
的表Table: users
--------+----------+----------+----------
user_id | username | password | user_type
--------+----------+----------+----------
1 | admin | neehahs | organizer
2 | student1 | mypass | student
然后您可以编写如下查询:
SELECT
user_type
FROM
users
WHERE
BINARY username='$username' AND
BINARY password='$password'
然后你的if:else if:else语句只会重定向返回是学生还是组织者;并且没有返回的行等于无效登录。
注意:强>
使用BINARY
与登录进行比较以确保用户名输入区分大小写,并且您应该在密码字段md5上使用某种加密,但强烈建议使用更强的加密
编辑:以下是我编写此逻辑的方法:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$user="admin";
$pass="neehahs";
$host="localhost";
$db="login";
$con=mysqli_connect($host,$user,$pass,$db);
if(mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username=($_POST['username']);
$password=md5($_POST['password']);
$username = mysqli_real_escape_string($con,$username);
$password = mysqli_real_escape_string($con,$password);
$sql="SELECT user_type FROM members WHERE BINARY student_id='$username' AND BINARY student_pass='$password'";
$sqldata=mysqli_query($con,$sql) or die ("error");
$row = mysqli_fetch_array($sqldata);
if(is_null($row) || mysqli_num_rows($sqldata)!=1){
echo "Sorry, your credentials are not valid or matches more than 1 user, Please try again.";
} else if(isset($row["user_type"])){
if($row["user_type"]=='student'){
header('location: http://localhost/greenstudio/index.html');
} else if($row["user_type"]=='organizer'){
header('location: http://localhost/greenstudio/index2.html');
} else {
echo "User type was returned as not student nor organizer.";
}
} else {
echo "Sorry, user_type was not returned in the dataset retrieved from the database.";
}
}
?>