0

I have to get the user ID from the database, but the only session information I can get from the login page is the username and the password. I am able to get the username, but when I try to run a query to get the id using that info, it returns nothing. Here is the code:

$_SESSION['username'] = $username;

 $connect = mysqli_connect("xxxx","xxxx","xxxx", "xxxx");

          $IDquery = "SELECT UserID FROM User WHERE Username = ".$username.";";

          $result = $connect->query("SELECT UserID FROM User WHERE Username = '$username';");

          if(mysqli_num_rows($result) > 0 ){

            $row = mysqli_fetch_assoc($result);
            $user_id = $row["UserID"];

            $_SESSION["UserID"] = $user_id;
          }

How can I get the user ID if I only have the username?

GMB
  • 216,147
  • 25
  • 84
  • 135

2 Answers2

0

I do suspect that this:

$_SESSION['username'] = $username;

Should actually be:

$username = $_SESSION['username'];

That is: you want to retrieve the username from the session rather than setting the session variable.

Side note: you should really use parameterized queries rather than mungling variables into the query string. This is more efficient, and safer, as it prevents you from SQL injection. You can have a look at this famous SO post for the whys and hows.

GMB
  • 216,147
  • 25
  • 84
  • 135
0

It looks like the issue is how you are trying to use the $username variable into the query (you should also, as mentioned before, use parameterized queries). First of all, make sure that before sending the $username you know what's is inside it. try for example:

var_dump($_SESSION['username']);

Put it before you execute the query. Sometimes it helps to remove variables from the middle if not sure how it is being assigned:

$IDquery = "SELECT UserID FROM User WHERE Username = ".$_SESSION['username'].";";

Also, you want to be sure that the session is filled with the information you are going to use at the same time the user is authenticated. that should remove queries in the middle of the session.

nitzer
  • 11
  • 1