PHP session gets a value other than what MySQL gives

I’m trying to check admin privilege of the logged in user (login.php):

 $sql2 = "SELECT admin FROM signup WHERE username = '$username' and password = '$password' limit 1";
if ($count == 1) {

                $_SESSION['loggedin'] = true;

                $_SESSION['username'] = $username;

                $_SESSION['is_admin'] = (int)mysqli_query($connection, $sql2);

                header("Location: ../home/index");

            }

and in index.php:

<div class="main-menu">

          <ul>

            <li>

              <?php

              if (!isset($_SESSION['loggedin']) && !isset($_SESSION['username'])) {

                echo "<a href='/MyProject/public/login/index'>LogIn</a>";

              } else {

                echo "<a href='/MyProject/public/logout/index'>Logout</a>";

                echo "<li>";

                if ($_SESSION['is_admin'] == 1) {

                  echo "<a href='/MyProject/public/admin/index'>Admin Area</a>";

                  echo $_SESSION['is_admin'];

                  echo "</li>";

                }

              } ?>

The problem is that session shows value of 1 (admin column) while the value in the MySQL is 0.
Whatis wrong in my code?

This code makes no sense at all. This is your process.

You create a query.
NEVER execute it.
Check for results, which can NEVER be anything except null.
Then, you set some values, which never get set because the query never got executed.
Then, you attempt to run a query and set a variable to it.

This would never ever run or ever do anything. You need to execute the query after you create it.
Then, you need to fetch the data to see if there is actually data in the results from the query.
Then, if there is some results, process the data and set up the login info.

Rewrite your logic to actually execute the query. Good luck!

1 Like

In your login code, the only user value you should store in a session variable is the user_id (auto-increment integer primary index.) Then, upon each page request, test for the session user_id variable and use it to query for any other user data. This will insure that any changes made to that user data will take affect on the very next page request.

Also, you should be hashing the password. See php’s password_hash() and password_verify().

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service