Domenic Fiore
Domenic Fiore

Reputation: 544

MySQLi stmt num_rows returning 0

I'm having an issue with using $stmt->num_rows in PHP and I'm not sure what I'm doing wrong. $stmt->num_rows is returning 0 when it should be returning 1. The query does work and returns 1 result when executing it in phpMyAdmin. Any help would be greatly appreciated.

public function get_login($username, $password)
{
    $query = "SELECT `id` FROM `users` WHERE `username` = ?";
    $stmt = $this->prepare($query);
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->bind_result($id);
    $stmt->fetch();
    $stmt->store_result();
    if($stmt->num_rows > 0)
    {
        return $id;
    }
    return false;

}

Upvotes: 5

Views: 6569

Answers (1)

Iswanto San
Iswanto San

Reputation: 18569

Try this, call the get_result first, then fetch the result.

public function get_id($username)
{
    $query = "SELECT `id` FROM `users` WHERE `username` = ?";
    $stmt = $this->prepare($query);
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();          
    return $row['id'] ?? false;
}

Upvotes: 15

Related Questions