0

I am getting two annoying undefined index lines. I was trying to fix these.

Notice: Undefined index: user in C:\xampp\htdocs\lynnletbo\diarypanel\login.php on line 4 Notice: Undefined index: pass in C:\xampp\htdocs\lynnletbo\diarypanel\login.php on line 5

login.php

<html>
<body>
    <form method = "post" action = "login.php">
    <input type = "text" name = "user" placeholder = "Username" />
    <input type = "password" name = "pass" placeholder = "Password" />
    <input type = "submit" name = "submit" value = "Login" />
    </form>
</body>

The above code is a form where I can login.

Here is the following code that I use to check from Database and login.

<?php
require('../db_connect.php');
session_start();
$username = $_POST['user'];
$password = $_POST['pass'];
if(isset($_POST) && $username != '' && $password != '') {
    $sql = $database->prepare("SELECT `user_id`, `user_password` FROM `users` WHERE `user_name` = ?");
    $sql->execute(array($username));
    if ($row = $sql->fetch()){
        $_SESSION['username'] = true;
    }
    else {
        echo "Can't login";
    }
}
?>
Kaung Myat Lwin
  • 1,049
  • 1
  • 9
  • 23

2 Answers2

2

Its simple, just check whether these indices exists in POST before processing the form.

Normally, $_POST values are unpopulated on initial load, so assigning them on load will spew that undefined index error.

<?php

require '../db_connect.php';
session_start();

if (!empty($_POST['user']) && !empty($_POST['pass'])) {

    // then continue
    $username = $_POST['user'];
    $password = $_POST['pass'];
    $sql = $database->prepare("SELECT `user_id`, `user_password` FROM `users` WHERE `user_name` = ?");
    $sql->execute(array($username));
    if ($row = $sql->fetch()) {
        $_SESSION['username'] = true;
        // handle password matching here
    }
    else {
        echo "Can't login";
    }


}

?>

There are some intricacies that goes into this. If you'd like to know those, I suggest visit deceze's article to know more.

Kevin
  • 41,694
  • 12
  • 53
  • 70
-1

$_POST['pass'] should be $_POST['password'] as same as you named that field

wijaya
  • 152
  • 7