php - PDO 在函数外工作,在函数内不起作用

标签 php mysql function pdo

我正在尝试验证 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);

最佳答案

您还必须将在函数内部使用的其他变量传递给该函数。

因此,正确的函数应该是:

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);

关于php - PDO 在函数外工作,在函数内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692397/

相关文章:

c - c语言中如何将代码分成函数

sql - 检查后从表中返回值的 PL/SQL 函数

javascript - 如何提高这个JS函数的速度

php - WooCommerce:检查产品是否具有特定属性

python - sqlalchemy.orm.exc.FlushError : Instance has a NULL identity key 错误

php - SQL 和 Codeigniter 计算定期付款的复利

mysql - 在 Drupal 中过滤 theme_table

java - 加密货币

php - 计算两个日期之间超过 1 小时的天数再加 1 天

php - Symfony2 将选定的日期从表单保存到数据库作为 DateTime