我正在尝试验证PDO中的登录,但它在函数内部时不起作用。我已经尝试将$db
添加到该函数中,但没有帮助。无论发生什么,它都会回应“坏”,如果我从函数中删除它,它可以使用完全相同的代码。这就是整个事情:
function logIn($db)
{
try
{
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE Username = :user AND Usernameclean = :userclean AND Password = :pass");
$stmt->bindParam(":user", $user);
$stmt->bindParam(":userclean", $userclean);
$stmt->bindParam(":pass", $pass);
$stmt->execute();
$status = (bool) $stmt->fetchColumn(0);
if ($status)
{
echo "good";
}
else
{
echo "bad";
}
}
catch (PDOException $e)
{
echo "There was a problem connecting to this database.";
$e->getMessage();
}
}
logIn($db);
答案 0 :(得分:4)
您还必须将函数内使用的其他变量传递给该函数。
因此,正确的功能是:
function logIn($db, $user, $userclean, $pass)
{
try
{
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE Username = :user AND Usernameclean = :userclean AND Password = :pass");
$stmt->bindParam(":user", $user);
$stmt->bindParam(":userclean", $userclean);
$stmt->bindParam(":pass", $pass);
$stmt->execute();
$status = (bool) $stmt->fetchColumn(0);
if ($status)
{
echo "good";
}
else
{
echo "bad";
}
}
catch (PDOException $e)
{
echo "There was a problem connecting to this database.";
$e->getMessage();
}
}
logIn($db, $user, $userclean, $pass);
答案 1 :(得分:3)
您记得将$db
变量传递给该函数,但忘记了$user
,$userclean
和$pass
,因此您的函数无法使用它们(它们已经用完了)范围)。
幸运的是,这很容易解决:
function logIn($db, $user, $userclean, $pass)
答案 2 :(得分:1)
您似乎没有传递$user
,$userclean
或$pass
个变量。
确保将它们传递给您的函数(或者,至少将它们全局化)