Search code examples
phpsqlprepared-statement

How to exclude some data for some users?


I have a main admin with a value of 2 in the users table in the admin column. There are also regular admins with a value of 1, and users with a value of 0.

The main admin has the ability to appoint other users as admins and take admin rights. I have a user list page, I managed to make a SQL query so that none of the regular admins have the main admin displayed. I also want to make sure that the regular admin is not displayed for other regular admins, but is displayed for the main admin. How to do it? Does SQL have exceptions? I read something about EXCLUDE, but I don't know yet if it will help me. Any ideas for an easier way to do this?

$ceo = 2;
$sql = $connection->prepare("SELECT id, name, email, admin, position, blocked, deleted FROM workers WHERE email!=? AND admin!=?");
$sql->bind_param("si", $_SESSION['user'], $ceo);
$sql->execute();
$users_listdb = $sql->get_result()->fetch_assoc();

$ _SESSION['user'] contains the email address of any authorized user.


Solution

  • You could just use if statements to update the SQL Query based on the user's level.

    Assuming the user is logged in and the user's id is an $id variable.

    // User ID's 
    $main_admin_id = 2;
    $admin_id = 1;
    $user_id = 0;
    
    $sql = "SELECT id, name, email, admin, position, blocked, deleted FROM workers WHERE email != ?";
    if ($id == 1) $sql .= ' AND (admin = ? OR admin = ?)';
    else if ($id == 0) $sql .= ' AND admin = ?';
    
    $stmt = $connection->prepare($sql);
    
    if ($id == 0) $stmt->bind_param('si', $_SESSION['user'], $user_id);
    else if ($id == 1) $stmt->bind_param('sii', $_SESSION['user'], $main_admin_id, $admin_id);
    else $stmt->bind_param('s', $_SESSION['user']);
    
    $stmt->execute();
    $users_listdb = $sql->get_result()->fetch_assoc();