mardi 6 octobre 2020

If multiple if conditions are true, run code

I have to create a 'as simple as possible' PDO register page for a project, but right now when a user fills only the username he logs in.

So the problem is that when a user only fills in a username the user will be able to log in, and i want to be able to run a session when the username and password are correct.

I tried already to add the && operators but that did not work
DISLAIMER: I am a beginner so the code mistakes are huge.

<?php
$database_host   = 'localhost';
$database_name   = 'database';
$database_user   = 'root';
$database_pass   = '';
$db_conn = new PDO("mysql:host=$database_host;dbname=$database_name", $database_user, $database_pass);

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


$sql = "SELECT * FROM `users`";
$stmt = $db_conn->prepare($sql); //send to mysql
$stmt->execute();

$users = $stmt->fetchAll();

foreach($users as $user)
{
    if($user['username'] == $username)
    {
      session_start();
      $_SESSION['id'] = $user['id'];
        header("location: home.php?login=success");
    }
    if($user['password'] == $password)
    {
      session_start();
      $_SESSION['id'] = $user['id'];
        header("location: home.php?login=success");
    }
    elseif($user['username'] !== $username)
    {
        header("location: index.php?error=usernameerror");
    }
    elseif($user['password'] !== $password)
    {
        header("location: index.php?error=passworderror");
    }
}
?>

Aucun commentaire:

Enregistrer un commentaire