Reputation: 57
I'm new to web development and I'm trying to make a login using PHP. The content of mylogin.php is getting processed immediately just after loading the file index.php, I'm a bit confused in here. Thie screenshot below is the reponse just after loading the index file.
response just after loading the index.php without doing anything
index.php
<!DOCTYPE html>
<html>
<head>
<title>
Welcome
</title>
</head>
<body>
<h1> Please login</h1>
<br>
<!--
<form action="" method="POST">
<label>Username: </label><br>
<input type="text" name="username" placeholder="Enter username"/><br>
<label>Password: </label><br>
<input type="password" name="password" placeholder="Enter password"/><br><br>
<input type="submit" name="submit" value="Login"/><br><br>
</form>
-->
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>
<?php
include("mylogin.php");
?>
mylogin.php
<?php
include("myconnection.php");
$error="";
if(empty($_POST["submit"]))
{
if($_POST["username"] =='' || $_POST["password"]=='')
{
$error='Please fill the blanks!';
}else
{
$username=$_POST['username'];
$password=$_POST['password'];
$sql="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result)==1)
{
$login_user=$_POST["$username"];
header("location: myhome.php");
$error="Connected";
}
else
{
//$error="Incorrect Username/Password";
// echo"failed";
}
}
}
else
{
echo"failed to submit2";
}
?>
Upvotes: 2
Views: 48
Reputation: 6565
Change the way you include mylogin.php
file like given in below code:
And there won't be this problem.
Welcome
<h1> Please login</h1>
<br>
<!--
<form action="" method="POST">
<label>Username: </label><br>
<input type="text" name="username" placeholder="Enter username"/><br>
<label>Password: </label><br>
<input type="password" name="password" placeholder="Enter password"/><br><br>
<input type="submit" name="submit" value="Login"/><br><br>
</form>
-->
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>
<?php
if(isset($_POST["submit"]))
{
include("mylogin.php");
}
?>
And of course, change your if
condition of your mylogin.php
file like this:
if(isset($_POST["submit"])) OR you can change it
if(!empty($_POST["submit"]))
Upvotes: 1
Reputation: 2471
You got a trouble with this condition if(empty($_POST["submit"]))
. You want the negative condition of this, so you need something like :
if(!empty($_POST["submit"]))
(with !
)
Upvotes: 2