Sebastian Ong Sebastian Ong - 3 years ago 39
MySQL Question

My login page is not working, if statement keeps activating nonetheless

<div class = "login">
<?php

$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];

$mysql = new mysqli("localhost", "root", null, "webdb");

$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();

if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
?>

<form action="sign in.php" method="post">

<div class = "details">
<br>
&nbsp<input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>

</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>






I've been working on my login page for a day but I cannot seem to find the error in my codes. Currently, when I click on login, it automatically activates the if statement "the log in is successful" without even having to key in the username and password.

Answer Source
<div class = "login">
<?php
if(isset($_POST['submit'])){
    $lusername=$_POST['lusername'];
    $lpassword=$_POST['lpassword'];

    $mysql = new mysqli("localhost", "root",'', "webdb");

    $stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
    $stmt->bind_param("s", $lusername);
    $stmt->execute();
    $stmt->bind_result($u, $p);
    $stmt->fetch();
    $stmt->close();
    $mysql->close();

    if($lusername == $u && $lpassword == $p) {
        echo "the log in is successful";
    }
    else {
        echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
    }
}
?>

<form action="sign in.php" method="post">

    <div class = "details">
  <br>
  &nbsp<input type="text" name="lusername" placeholder="Username" required>
  <br>
  <br>
  <br>
  <input type="password" name="lpassword" placeholder ="Password" required>

</div>
<div class = "enter">
  <br>
  <br>
  <input type="submit" name="submit" value="Enter">
</div>

try this as you are first checking the GET request, and it will always give the login successful, for that you need to check whether the submit button has been pressed, and remove the null from the database password as for blank password you keep '' and not null

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download