MySQLi stmt num_rows返回0

时间:2013-02-07 00:02:58

标签: php mysql mysqli

我在PHP中使用$stmt->num_rows时遇到问题,我不确定我做错了什么。当{1>}返回时,$stmt->num_rows返回0.查询执行工作,并在phpMyAdmin中执行时返回1结果。任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:11)

试试这个,首先调用store_result,然后调用fetch结果。

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