简体   繁体   中英

PHP & MySQL: How do I compare the user input to data in the database?

I have a HTML form with a textbox where you enter a username, and a login button. When the user presses the login button, I want the database to be queried and if there is a match echo out a statement. The code I have is this:

<form class="login_box" method="POST">
        <input id="input-boxes1" type="text" name="username" value="" placeholder="Username">
        <input id="button-1" type="submit" name="login" value="Login">
    </form>


// Checks if login button is pressed
    if (isset($_POST['login'])) {
      $enteredUser = $_POST['username'];

      $sql = "SELECT * FROM user WHERE username='$enteredUser'";
      if ($result = mysqli_query($link, $sql)) {
          echo 'it works';
      }
    }

What I want it to do is echo out "it works" if there is a match. However it always echoes it out no matter what. The database is working as intended as I have added to it and selected from it in other files, and the database is correctly linked to this form as well.

Any help would be great, thanks!

Thank you to @El_Vanja and @droopsnoot for helping. I've managed to figure out the solution now. As they rightly pointed out, I had to see if the number of rows returned was 1 and then echo out the statement if so.

My amended code is as below:

if (isset($_POST['login'])) {
      $enteredUser = $_POST['username'];

      $sql = "SELECT * FROM user WHERE username='$enteredUser'";
      $result = mysqli_query($link, $sql);
      if (mysqli_num_rows($result) == 1) {
          echo 'it works';
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM