print_r返回1但是没有保存记录

时间:2015-03-25 02:49:03

标签: php mysql pdo

我有一些保存记录的方法,包括用户令牌和电子邮件,如下所示:

public function saveResetToken($email, $resetToken)
    {
        try {

            $conn = Database::getConnection();
            // Connect and create the PDO object
            $conn->exec('SET CHARACTER SET utf8');      // Sets encoding UTF-8
            // Define and prepare an INSERT statement
            $sql = 'UPDATE users SET reset_token=:token WHERE email =:email limit 1';
            $stmt =$conn->prepare($sql);

            // Adds value with bindParam
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->bindParam(':token', $resetToken,PDO::PARAM_STR );

            if ($stmt->rowCount()===1){   

                $conn = null;        // Disconnect
                return true;

            }else{
                return false;
            }

        } catch (PDOException $e) {
            include('../views/error.php');
            include('../views/admin/includes/footer.php');
            exit();
        }
    }

当我使用print_r $ stmt-> rowCount()时,它返回'1',但是当我在reset_token检查时,我找不到数据。那我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

经过一些调查后,我意识到你问为什么当你期待1时这个函数为什么会返回true。当你的函数返回true时,它实际上返回1.所以它将返回1但如果你if($user->saveResetToken($email, $activation)) print('this is true'),你可以看到它实际上是评估为真。

试试这个:

function myFunc() {
  return true;
}
echo myFunc(); // output: 1
echo myFunc()==true; // output: 1
echo myFunc()==1; // output: 1
echo myFunc()===true; // output: 1
echo myFunc()===1; // output: 1

在php中true实际上意味着不是零。

以下是文档中被视为false的值:

  

转换为布尔值时,以下值被视为FALSE:

     

the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables) SimpleXML objects created from empty tags

查看php docs on booleans了解详情。

至于未保存的记录,您必须使用我的评论中提到的查询->execute()

相关问题