-1

I'm still new to PHP and I want to create a login page which keeps track of the users (teacher and students). My code is already working, but I get some warnings if the user enters an invalid username and password. Does anyone know how to fix this?

Here is the warning:

$user_type=$_POST["type"];

Warning: Undefined array key "type"

$row["type"]=="teacher"

Warning: Trying to access array offset on value of type null 

$row["type"]=="student"

Warning: Trying to access array offset on value of type null 

Here is the code:

$username=$_POST["username"];
$password=$_POST["password"];
$user_type=$_POST["type"];

$sql="SELECT * FROM user WHERE username= '".$username."' AND password= '".$password."' AND 
type= '".$user_type."' ";
$result=mysqli_query($data,$sql);
$row=mysqli_fetch_array($result);

if($row["type"]=="teacher"){
    $_SESSION["type"]=$username;
    echo "teacher";
}elseif($row["type"]=="student"){
    $_SESSION["type"]=$username;
    echo "student";
}
Your Common Sense
  • 154,967
  • 38
  • 205
  • 325
Alex
  • 203
  • 1
  • 6
  • [undefined array key](https://stackoverflow.com/a/16675998/128761). – vee Jun 04 '22 at 06:52
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jun 04 '22 at 11:12
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Jun 04 '22 at 11:12

0 Answers0