Skip to content Skip to sidebar Skip to footer

How To Fetch Top Two Rows Values In Mysql And Compare It With Value Of Session User Variable?

I want to assign 2 employees with least employee id's as administrator in my project. How to fetch 2 rows with least employee id's from mysql and compare it with current session us

Solution 1:

Follow these steps,

1) Once user will register, first two users will be e.g. say, superadmin(1) and admin(2) rest all will be normal users.

2) Now when a user will login, you need to save those user data along with emp_id into session.

3) Now, authorization, means which user will have access to which pages, you will fire query like,

select emp_id from employee order by emp_id asc limit 2.

This query will give you only ids of those top users, which are registered at top regardless of 1 or 2 or any number.

4) Check if current user's emp_id(which you have stored in session) exists in top two user's emp_id from query which you above wrote,

if exists,

then access to all page,

else

show an alert message, that you are not authorized or just redirect to your home page if any.

I am sure, you are now done with everything, if you follow these steps.


Solution 2:

Well to get first two employee you can use ORDER BY clause in query as:

SELECT * FROM employee_table ORDER BY EMP_ID ASC LIMIT 2

Now you can match the session user with the EMP_ID which you will get as a part of result after this query.


Solution 3:

for this exact example the sql would be:

 $bHasAdminAccess = db::getValue("SELECT count(*) FROM _USER_TABLE_ WHERE userid = ".$userIdLoggedIn." AND userid IN (SELECT userid FROM _USER_TABLE_ LIMIT 2)");

well the question should be, why the first two? Can't you simply say lower than two?

$bHasAdminAccess = db::getValue("SELECT count(*) FROM _USER_TABLE_ WHERE userid = ".$userIdLoggedIn." AND userid <= 2");

In case the id's could change, i would simply add another column "is_admin", so the table would look like:

  1    |  Mike   |  1
  2    |  Peter  |  1
  3    |  Drake  |  0
  4    |  Oliver |  0
  5    |  Andrew |  0

Than the code would be:

$bHasAdminAccess = db::getValue("SELECT count(*) FROM _USER_TABLE_ WHERE userid = ".$userIdLoggedIn." AND is_admin = 1");

Post a Comment for "How To Fetch Top Two Rows Values In Mysql And Compare It With Value Of Session User Variable?"