Reputation: 1400
I'm trying to validate login in PDO, but it doesn't work while it's inside a function. I've tried adding the $db
to the function as well, doesn't help. It echoes "bad" no matter what happens, if I remove it from the function, it works fine with the exact same code. Here's the whole thing:
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);
Upvotes: 0
Views: 171
Reputation: 10754
You must also pass other variables you are using inside the function to that function.
Therefore, the correct function would be:
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);
Upvotes: 4
Reputation: 622
You don't appear to be passing the $user
, $userclean
or $pass
variables.
Make sure you pass those to your function (or, at the very least, globalise them)
Edit: John beat me to it!
Upvotes: 1
Reputation: 219814
You remember to pass your $db
variable to the function but forgot about $user
, $userclean
, and $pass
so they are not available to your function (they are out of scope).
Fortunately this is easy to fix:
function logIn($db, $user, $userclean, $pass)
Upvotes: 3