I am trying to display an error message in php ( $error="Username or Password is invalid"; ) when the username or password is not in the database. But without even running the code(clicking login in index.php the error message is displaying. Thanks :)
<?php
    session_start(); // Starting Session
    $error=''; // Variable To Store Error Message
    if (isset($_POST['submit'])) {
    }
    if (isset($_POST['submit'])) {
    // Define $username and $password
     $name=$_POST['username'];
     $pass=$_POST['password'];
    $servername = "localhost";
    $username = "root";
    $password = "root";
    $dbname = "company";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT id, username, password FROM login";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            //echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
            if($name==$row["username"] && $pass== $row["password"]){
                header("location: profile.php"); // Redirecting To Other Page
            }else{
                $error="Username or Password is invalid";
            }
        }
    }
         else {
        echo "Server is down";
    }
    $conn->close();
    }
    ?>
My index.php
<?php
include('../php/login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
 
     
     
    