I have a mysql table called users
with the following fields:
username - password - role
The role consists of normal user and admin.
What I want is so when an admin logs in it gets redirected to another page and not the same page a normal user would log in. My code is as follows:
<?php
include("../includes/db.php");
$username=$_POST['username'];
$password=$_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM Users WHERE username='$username' and password='$password' And role = 'normaluser'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
session_register("username");
session_register("password");
header("location:myaccount.php");
}
?>
I have the code working for the normal user but I just don't know how to write the code for the admin part.
I'd say
$sql="SELECT role FROM Users WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
while ($row = mysql_fetch_object($result)) {
//one hit i hope?!
//DONT save your apssword in the session!!!!
//session_register("username");
//session_register("password");
$role = $row->role;
}
if($role == "user"){
redirect1
}elseif($role == "admin"){
redirect2;
}else{
redirect panic
}
Retrieve role
from the query, check to see what it is, then set the header location accordingly.
$sql = "SELECT * FROM Users WHERE username='$username' and password='$password'";
// ...
if($count == 1){
$user = mysql_fetch_array($result);
if ($user['role'] === 'normaluser')
{
session_register("username");
session_register("password");
header("location:myaccount.php");
}
if ($user['role'] === 'admin')
{
header("location:admin.php");
}
}
define some constants like below or use the bitmasking algoritim. (php_manual).
index.php or if your using a framework check the docs.
define('USER_ADMIN', 'a');
define('USER_USER', 'u');
build a permissions table with type text set to null
`permissions` text null
to build your user_permissions row in your views use the checkbox's
<input type="checkbox" name="permissions[]" value="u" selected />
<input type="checkbox" name="permissions[]" value="a" selected />
assigning data
$user='';
$user = (isset($_SESSION['uid'])) ? User::find($_SESSION['uid']) : '';
if(isset($user) && in_array(USER_ADMIN, $user['permissions']))
{
//i am an admin
}
else
{
//i am NOT an admin
}