I am attempting to learn prepared statements and OO MySqli.
My code throws an
Uncaught Error: Call to a member function bind_param() on bool in
that can be fixed by reconnecting to the database.
Here's my code:
$con = new mysqli("localhost", "DB", "MYUSER", "MYPASS");
$stmt = $con->prepare("SELECT 1 FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $_POST["user"], $_POST["pass"]);
$stmt->bind_result($exists);
$stmt->execute();
$stmt->fetch();
if ($exists)
{
//$con = new mysqli("localhost", "DB", "MYUSER", "MYPASS");
$sesh = uniqid();
$stmt = $con->prepare("UPDATE users SET sessionID = ? WHERE username = ? AND password = ?");
$stmt->bind_param("sss", $sesh, $_POST["user"], $_POST["pass"]);
$stmt->execute();
echo "User found, sessionID set.";
}
else
{
echo "User not found.";
}
$con -> close();
This code will throw the error, but if I uncomment //$con = new mysqli("localhost", "ganzo", "liamjacobs14", "ganzo");
then it works perfectly.
What could be the possible reason behind this? Is there something I don't know about on of these functions that would lead to it closing the connection unexpectedly? Please advise.
P.S. I'm aware I should be hashing my passwords, but for the sake of simplicity in learning how all of this works, I'm leaving them as plain text for now.
EDIT: I accidentally forgot to censor my username and password in the second connection. The information is exactly the same. The database is exactly the same. The proposed answer is not applicable here.