Search code examples
phpmysqlwhile-loopsession-variables

php session and while-loop: undefined index


I am trying to pass a variable through a session. I use a while loop to run through a database, which works perfectly. If $username and $password are correct I always get these error notices:

Notice: Undefined index: GELD in login.php on line

Notice: Undefined index: NIVEAU in login.php on line

Why do I get these error notices and how could I resolve them?

index.html

<form id="loginform" method="post" action="login.php">
    <img src="afbeelding/logo.png">
    <label for="username">
        Username
    </label>
    <input id="username" type="text" name="username"/>
    <label for="password">Password</label>
    <input id="password" type="password" name="password"/>
    <input type="submit" value="Login">
</form>

login.php

<?php
    session_start();
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['password'] = $_POST['password'];
    $dbhost = 'sql7.xxx.net';
    $dbuser = 'xxx';
    $dbpass = 'xxx';
    $db = 'xxx';

    $username = $_SESSION['username'];
    $password = $_SESSION['password'];

    $con = mysql_connect($dbhost, $dbuser, $dbpass);
    $db_found = mysql_select_db($db, $con);
    $result = mysql_query("SELECT ID, USERNAME, PASSWORD FROM Game");

    $username = $_SESSION['username'];
    $password = $_SESSION['password'];

    while ($row = mysql_fetch_array($result)) {
        if($row{'USERNAME'} == $username){
            if($row{'PASSWORD'} == $password){
                $_SESSION['geld'] = $row{'GELD'};
                $_SESSION['niveau'] = $row{'NIVEAU'};
            }
            else{
            }
        }
    }
?>

Solution

  • SELECT ID, USERNAME, PASSWORD FROM Game - there you didn't select the GELD and NIVEAU columns in your query. and don't use a deprecated MySQL API.

    Use mysqli with prepared statements, or PDO with prepared statements.

    Passwords

    If you're live with this or intend on going live with plain text password, STOP right there.

    For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.

    For PHP < 5.5 use the password_hash() compatibility pack.

    Also consult the manual on password_verify().

    Sidenote about using password_hash() and column length.

    If and when you do decide to use password_hash() or crypt, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.

    You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.