0

Im trying to retrieve the correct user_id for my user who is logging in to my website...

$result = $conn->prepare("SELECT * FROM users WHERE email_address= :em AND password= :pw");
$result->bindParam(':em', $user);
$result->bindParam(':pw', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
    $_SESSION['loggedin'] = 1;
    $_SESSION['uid'] = $rows['user_id'];
}

I want to get the relevant user_id and im trying to do so using $rows['user_id']; with no luck...

2
  • What does fetch() return? I think it's a result pointer rather than an array - you have to explicitly fetch the array. It also looks like you're returning ALL rows instead of just one, so $rows['user_id'] would be undefined ($rows[0]['user_id'] might work) Commented Feb 27, 2014 at 1:15
  • 1
    You might try PDO::FETCH_ASSOC instead. "PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0" php.net/manual/en/pdostatement.fetch.php Commented Feb 27, 2014 at 1:17

1 Answer 1

2

You should use PDO::FETCH_ASSOC instead of PDO::FETCH_NUM

And fetch return false when there is no result more, so you should do like:

$result->execute();
if ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $_SESSION['loggedin'] = 1;
    $_SESSION['uid'] = $rows['user_id'];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.