Difficulty in Fetching data for logged in user

31 Views Asked by At

Here is my login process, I want a same dashboard but data will be different for each user. But I am stuck with creating uid variables to get data for each login user.

if(isset($_POST['login_btn']))
{
    $email_login=$_POST['email'];
    $password_login=$_POST['password'];
    $admin="admin";
    $co_admin="co_admin";

    $query = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$admin' ";
    $query_run = mysqli_query($connection, $query);

    $query_co = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$co_admin' ";
    $query_run_co = mysqli_query($connection, $query_co);

    if(mysqli_fetch_array($query_run))
    {
        $_SESSION['username'] = $email_login;
        $_SESSION['usertype'] = $admin;
        header('Location: index.php');
    }
    else if(mysqli_fetch_array($query_run_co))
        {
         $_SESSION['username'] = $email_login;
         $_SESSION['usertype'] = $co_admin;
         header('Location: company_view.php');
        }
       
    else
    {
        $_SESSION['status'] = 'Email ID / Password / User Type is Invalid';
        header('Location: login.php');
    }

    

    
}

Above source code is for separating Co-admin and Admin. Now Any Co-Admin login to the portal he should get his own details, I would like to know which function I have to call or how should I declare a uid variable to fetch data tables for each current logged in user. I found some other source codes but which is not related to me so i am confused with how I fix it with those code. Can anyone do it in my codes.

1

There are 1 best solutions below

1
Robert Egginton On

I think you are asking how to get data for the current user from mysql tables. Yes, the standard way of doing this is via a unique ID for each user that is pulled from the registered_users table, storing this in the session, and then referencing this in the other tables and filtering by this ID. I would not suggest storing anything else from this table in the session as the ID is likely to have a stronger guarantee of imutibility.

For example if you have a table of recently visited pages per user, you would get this via:

$query = 'SELECT * from recently_visited WHERE user_id = ?';
$stmt = mysqli_prepare($query);
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();

You can check the mysqli documentation for how to then extract what you need from the executed statement. I've shown this example of a prepared statement so you can see how to avoid SQL injection as well.

You may want to look into using foreign keys to enforce this connection.