jeudi 2 janvier 2020

If statment in foreach only checking the last value

I am trying to make a login system using php that checks the username and password in a database. But the problem is that my if statment that is in a foreach only checks the last value in my database. For instanse if i had 5 users with usernames and passwords in my database, the if statment in my foreach only checks if i typed in the username and password of the last user, but if i give it a username and password of let's say the second user, it will not accept it.

html code:

<!DOCTYPE html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Login</title>
</head>

<body>
  <div class="top">
    <div class="box">
      <h2>Login</h2>
      <form action="findAccount.php" method="post">
        <div class="inputBox">
          <input type="text" name="username">
          <label>Username</label>
        </div>

        <div class="inputBox">
          <input type="password" name="password">
          <label>Password</label>
        </div>

        <input type="submit" name="submit" value="Submit">
      </form>
    </div>
  </div>
</body>

</html>

php code:

<?php
$dbh = new PDO('mysql:host=localhost;dbname=database_name', 'root', '');

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

$sql = $dbh->prepare("SELECT * FROM tabel_name");
$sql->execute();
$result = $sql->fetchAll();

foreach ($result as $r) {
  if ($username == $r['username'] && $password == $r['password']) {
    header('Location: mainPage.php');
  } else {
    header('Location: login.php');
  }
}

Aucun commentaire:

Enregistrer un commentaire