2

I'm writing a class, but I stucked in a function. It requests the email address by username, but it's only returning null.

Code:

private function getUserEmail($username){
    if($stmt = $this->_mysqli->prepare("SELECT email FROM users WHERE username='?'")){
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($email);
        $stmt->fetch();
        var_dump($email);
        $stmt->close();
        return $email;
    }
}
5
  • 1
    Did you check if the query is actually executing? Actually returning any data? Your code is simply assuming success throughout. Commented Aug 16, 2013 at 19:39
  • @MarcB $stmt->execute() returns true. Commented Aug 16, 2013 at 19:47
  • I checked if $stmt->fetch returns error, but it returns null, so I think the problem is somwhere there. Commented Aug 16, 2013 at 19:49
  • getting null from the ->fetch() call means that there's no data at all (or you've fetched all available data already): php.net/manual/en/mysqli-stmt.fetch.php. Do a echo $stmt->num_rows() right after the ->execute() call. If you get 0, then you've just got no data at all. Commented Aug 16, 2013 at 19:52
  • It's returning 0, but there's data in the users table. Commented Aug 16, 2013 at 19:54

1 Answer 1

1

Try removing the single quotations around the ?

if($stmt = $this->_mysqli->prepare("SELECT email FROM users WHERE username=?")){

Otherwise it won't recognize the ? as a placeholder.

See documentation on syntax here: "The ? characters should not be enclosed within quotation marks, even if you intend to bind them to string values."

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks for the help. I removed the quations, and now the code is working.

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.