I’m relatively new to php / mysqli i’m having trouble authenticating the user, I’m not exactly sure how to fetch a row and validate the data against it, then redirect user to a new page or display an error(all i know is i need to use _SESSION) . Basically i’m having trouble with the fetch() routine, what is the right way to code this?
<?php
session_start();
$username = trim($_POST['username']);
$password = trim($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT Login_ID, Login_PW,
FROM login
WHERE Login_ID=? AND Login_PW =?"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, $password);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($username, $password);
/* Fetch the value */
if($stmt->fetch() == true)
{
$row =$query -> fetch();
$_SESSION['name'] = $row;
header("Location:/in.php");
exit();
}
else
{
echo 'Invalid Login';
}
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
Follow this order
$stmt->prepare()$stmt->bind_param("ss", $username, $password);$stmt->bind_result($username, $password)$stmt->fetch()$stmt->closeI think it isn’t clear to you that
$stmt->bind_result()already sets up variables. In your case you are likely to only fetch 1 row from the table, so$stmt->fetch()is enough. If you have multiple rows you need a loop which you use to use the data.example:
regarding the user and password match:
you now have
so you have have to make an if statement that checks
$_POST['username'] == $username && $_POST['password'] == $password. If this is true, you can set your loggedin flag.To keep a user logged in just set a $_SESSION variable. You could set
$_SESSION['logged_in'] = true;, this gives you the possibility to know the user is already authenticated if this variable is set. If user wants to end his session, just unset the variable (and destroy session).also one more thing I noticed: