Mysqli code to fetch one result and return it


I have a login site where users login with their emails. Each is assigned an auto-increment user_id. I want to fetch the associated user_id from the database and store it in the session so that when they submit content, their user_id can be gotten from the session and submitted with the content. However, my "get_user_id" function is not working to look up the user id from their email address. I’ve tried using all sorts of mysqli commands from fetch_row, get_result, bind_result, and nothing will return the user_id.

    function get_user_id($email) {
    //$email = mysqli_real_escape_string($this->conn, $email);
    $query = "SELECT id from users where email=?";
    if ($stmt = $this->conn->prepare($query)){
        if($result = $stmt->execute()){
            return $row['id'];
        } else return "no ID returned.";

The error message I am getting now is:

Fatal error: Call to a member function fetch_row() on a non-object


The variable $result will contain a boolean – a TRUE or FALSE.

You’re trying to call the function fetch_row() on that boolean, which won’t work.

If you’re using prepared statements, you should use bind_result() and then the fetch() function on $stmt.

Change $row=$result->fetch_row(); to$stmt->fetch(); and in stead of using the variable $row, call bind_result(), as described in the example here:

Answered By – RickN

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published