简体   繁体   中英

How to access the username of the user that is logged in

I have made a web application. I have completed the registration and login. There are two user types that can register, student or professor.

I have a session running from the login time until logout. If you login as a user there are certain things you can do. One of them is close an appointment. This can be done from a radiobuton in a loginstudent.php (for example) page and submit button. This leads you to another .php page. On that page I have to use the username of the user that is logged in (in my case that would be the student) for a mysql query. I don't know how to access this.

 $sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username=$username);";

I think this is wrong.

edit this is the complete login

<?php

session_start();

if (($_POST['submit'])) {

    include_once 'dbh.php';

    $username = $_POST['username'];
    $password = $_POST['password'];


    //check if empty

    if (empty($username) || empty($password)) {
        header("Location: http://localhost/TexnologiaLogismikou/index.php?login=empty");
        die;
        exit();
    } else {
        $sql = "SELECT * FROM user WHERE username='$username';";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result); // tsekarei posa vrethikan
        if ($resultCheck < 1) {
            header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
            die;
            exit();
        } else {

            if ($row = mysqli_fetch_assoc($result)) {
                $hash_password_check = password_verify($password, $row['password']);
                if ($hash_password_check == false) {
                    header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
                    die;
                    exit();
                } elseif ($hash_password_check == true) {
                    //login

                    if ($user_type=="student") {


                        $_SESSION['username'] = $row['username'];
                        $_SESSION['firstname'] = $row['firstname'];
                        $_SESSION['lastname'] = $row['lastname'];
                        $_SESSION['user_type'] = $row['user_type'];
                        header("Location: http://localhost/TexnologiaLogismikou/student.php?login=success");
                        die;
                        exit();
                    } else {

                        $_SESSION['username'] = $row['username'];
                        $_SESSION['firstname'] = $row['firstname'];
                        $_SESSION['lastname'] = $row['lastname'];
                        $_SESSION['user_type'] = $row['user_type'];
                        header("Location: http://localhost/TexnologiaLogismikou/professor.php?login=success");
                        die;
                        exit();
                    }
                }
            }
        }
    }
} else {
    header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
    die;
    exit();
}

then goes

<?php
include_once 'header.php';
?>

<script>

    $(document).ready(function () {
        $('#5').hide();

        $("form input:radio").change(function () {
            if ($(this).val() === "appointment") {
                $("#5").show();


            } else {
                $("#5").hide();

            }
        });





    });

</script>






<section class="main-container">
    <a href="footer.php"></a>
    <a href="dbh.php"></a>
    <a href="header.php"></a>
<div class="main-wrapper">
    <form class="student-form" action="studentphp.php" method="POST">
        <link href="style.css" rel="stylesheet" type="text/css"/>
        <h4 id="9">Select your action:</h4><br>

        <input type="radio" name="action" value="appointment">
        <p id="8">Show your Appointments</p><br>
        <input id="5" type="text" name="prof_last" placeholder="Professor Lastname">
        <input id="6" type="radio" name="action" value="upload">
        <p id="7">Upload a File</p><br>

        <input type="submit" name="submit">
    </form>

</div>
</section>



<?php
include_once 'footer.php';
?>

and this is the page i need the username

<?php

include_once 'header.php';


if (($_POST['submit'])) {
    include_once 'dbh.php';

        $prof_last = $_POST['prof_last'];

    if (empty($prof_last)) {
        header("Location: http://localhost/TexnologiaLogismikou/student.php?professorlastname=empty");
        die;
        exit();
    } else {
        $sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username=$username);";
        mysqli_query($conn, $sql);


    }
} else {
    header("Location: http://localhost/TexnologiaLogismikou/student.php"); //se ksanapaei sto sign up
    die;
    exit();
}
?>
















<?php

include_once 'footer.php';

You state that you have login pages working, and sessions working.

A session is serverside storage tied to a connection. So the typical way to handle this (in simplest terms)

if (you accept that user logged in) {
    // From the database row you used to check username/password
    $_SESSION['userId'] = $row['user_id'];
} else {
    //Login failed
}

Depending on how you wrote your login check sql statement you might have to adjust it to include the user_id for this to work.

Once this is working, anytime you need the user_id of the currently logged in user, you have it available in the session. For a secured site, this might be on nearly every request.

Now your sql statement is simpler:

$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id={$_SESSION['userId']}";

Here's where I will admonish you that all your SQL statements should be using bound parameters rather than variables embedded in strings, but that is not the crux of your question.

Also you might be able to save yourself some time and code by storing an array to $_SESSION so that you don't need to set every user table variable individually.

You can do this:

$_SESSION['user'] = $row;

Then later you can reference:

echo $_SESSION['user']['username'];

well, if you store the username in the $_SESSION already, you can access it anywhere. Just make sure to call session_start() at the top of the PHP script every time you want to use it.

The approach i think you should use is: Firstly, i suppose that you have created some sort of 'user-roles' table to manage the different user access levels (for professor and for student). After a user has logged in with their username and password, you can access their account details (their real name or username, whichever), and save this value in the session variable. It will look like:

$_SESSION["username"] = "some-user-name";

You can store other info here as well, such as the user's real name, like:

$_SESSION["display-name"] = "the user's name";

When the logged-in user navigates to the any other page, you can get their information from the session variable like this:

$username = $_SESSION['username'];
$displayName = $_SESSION['display-name']; 

You can then do whatever you like with them.

After reading through the posted code, i think your goal is to help a student set up an appointment with a professor. And you would like to access the professor record in the database by matching it with the professor's last name. Correct me if i am wrong. If this is the case, then i advise you to change your approach slightly. Look at it like this. If a user logs in successfully (prof or student), store their user_id as well. It will help you later, like this:

$_SESSION["user-id"] = $row['id'] //or
$_SESSION["prof-id"] = $row['id'] //or

Secondly, when a student would want to set/close an appointment, i suggest that you:

  1. Read all the professors' full names and database ids from the the student's department (or from the database table) into an html select tag, something like [select value=""][/select]

This will save you from using the 'last-name' as a matching field in the database. Someone might write 'johns' or 'Johns', or even 'Johns '. These are all the same to a human reader but are different to the database.

You can assign the value field in the select tag to the database id of the professor, with the corresponding professor name.

Something like [select value="1"] Prof. Jonathan Andrews[/select] , etc

That way, there is no need for a student to type (or even know) the last name of the professor. They would select the professor's name.

Lastly, when reading the appointments from the database, you can use the professor id from the select tag and the student id from the session variable. If your select tag is named 'prof-id', you can get the POSTed value with:

$profId = $_POST['prof-id'];

#get the student id from the session var
$studentId = $_SESSION['user-id']

$newQuery = "SELECT * FROM appointment WHERE prof_id = $profId AND student_id = $studentId";

Let me know if understand this and can continue from there. If you need the code, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM