I have the following prepared statement:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
$stmt->fetch();
$stmt->close();
}
if ($pass === $filtered_form['pass']) {
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
$_SESSION['first'] = $first;
$_SESSION['last'] = $last;
$_SESSION['email'] = $email;
$_SESSION['type'] = $type;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
however Visual Studio says there is a problem that the variables $id, $user, $pass, $first, $last, $type, $email
are not defined. I added the variables like this:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$id = "";
$user = "";
$pass = "";
$first = "";
$last = "";
$type = "";
$email = "";
$stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
$stmt->fetch();
$stmt->close();
}
if ($pass === $filtered_form['pass']) {
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
$_SESSION['first'] = $first;
$_SESSION['last'] = $last;
$_SESSION['email'] = $email;
$_SESSION['type'] = $type;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
And the problem goes away. Upon reviewing the PHP documentation, I cant find examples where the variables must be defined first, yet visual studio still shows it as an error. Any idea why this is?
Nope, it is not necessary when variables are passed by reference, which is the case here. So it's Visual Studio who is wrong here.
However, you are using obsoleted techniques here, and can get rid of these false positive warnings and reduce the amount of code at once:
$stmt = $conn->prepare("SELECT * FROM `users` WHERE user = ? ");
$stmt->bind_param("s", $filtered_form['user']);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if ($row and password_verify($filtered_form['pass'], $row['pass']) {
$_SESSION['user'] = $row;
header("Location:index.php");
exit;
} else {
return "Incorrect password";
}
as you can see, get_result()
gives you a much better result (pun not intended) than store_result()
, letting you to store the user information in a single variable, so it won't litter the $_SESSION
array.
And num_rows()
proves to be completely useless (as it always happens).
An important note: you should never ever store passwords in plain text. Alwas shore a hashed password instead.