marijn marijn - 1 year ago 69
PHP Question

Not getting the expected user information

I'm trying to make an admin page and allow only users with role 2 for some reason its not giving me the information I expected.


$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: login.php');
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;

if($user['role'] == '2'){
echo "Hello $user['name']";
else {
header('location: index.php');

When I do
its giving me the output 1.

When I echo the
it is giving me the right id (the session id is the same as user id).

Answer Source

Right now what you have done is, you just executed the query and had the resultset stored in $user. You need to fetch the results from the Result Set.

$user = mysqli_fetch_array($user);

Now it should work as expected.

Update: You should also handle the following:

  • Sanitization: Make sure you use ' for the values and ` for the column names. Also use mysqli_real_escape_string() for escaping some obvious stuff.
  • Validation: That's the next most important. Try checking if the resultset has any rows returned. You can do by using mysqli_num_rows($user) > 0 or precisely in your case, mysqli_num_rows($user) == 1.
  • Variables: Here in the example, I have used the same $user for the Result Set as well as the row. It is always better to have two separate variables, say, $userRes (for result set) and $userData (for the fetched data).

Hope this should answer your question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download