PHP login with Mysqli

html, mysql, mysqli, php

Solution

Follow this order

- Prepare Query `$stmt->prepare()`

- Bind Param if you use placeholders `$stmt->bind_param("ss", $username, $password);`

- Execute

- Bind Results to variables `$stmt->bind_result($username, $password)`

- The data is now ready to be picked up with `$stmt->fetch()`

- Close prepared statement `$stmt->close`

I 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:

$a = array();
while ($stmt->fetch()) {
    $a = array('username' => $username, 'password' => $password);
}

regarding the user and password match: you now have

$_POST['username'];
$_POST['password'];
$username;
$password;

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:

if($stmt->fetch() == true) { } // equals: if ($stmt->fetch()) { }

Problem

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(); ?> ```

Original source