我最近开始学习PHP,遇到了一些麻烦。我在这里查看了其他一些答案,但仍然无法解决,所以很抱歉。
我正在尝试添加一个检查以查看用户帐户是否为管理员,然后如果是管理员页面,则直接进入管理页面,如果不是管理员帐户,则直接进入索引页面。在我的用户表中,我有一个名为“user_type”的列,管理员设置为“admin”。我将如何让我的登录代码检查并正确重定向?
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="db_tc"; // Database name
$tbl_name="tbl_users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// Password Hashing
$mypassword = hash("sha512", $mypassword);
//SQL injection protection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE email='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$ar=mysql_fetch_array($result);
if($ar['user_type']=='admin')
{
header('Location: admin.php');
}
else
{
header('Location: index.html');
}
// Count table rows.
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$_SESSION["login"] = ("usernameEntered");
header("location:index.html");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
更新答案:
谢谢大家的帮助。对于想要在此处查看最终工作代码的用户,它是:
$ar=mysql_fetch_array($result);
// Count table rows.
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
if($ar['user_type']=='admin')
{
header('Location: adminhome.php');
}
else
{
header('Location: index.html');
}
}
else {
echo "Wrong Username or Password";
}