skip to Main Content

I’m trying to get data from the database for my login page, but can’t seem to do so. It keeps on telling me that my username or password is wrong.

I’m a beginner in this field and got my codes from youtube.

form1.html

<!DOCTYPE html>
<html>
<head>
 <title>Login Site</title>
</head>
<body>
<form method="POST" action="connect2.php">
Username : <input type="text" name="username"><br><br>
Password : <input type="password" name="password"><br>
<input type="submit" value="Login" name="submit">
</form>
</body>
</html>

connect2.php

<?php
$con = mysqli_connect("localhost", "root", "") or die("Failed to connect to MySQL."); 
mysqli_select_db($con, "abc") or die("Database does not exist."); 
//require ('sql_connect.php');
if (isset($_POST['submit'])){
    $username=mysqli_escape_string($_POST['username']);
    $password=mysqli_escape_string($_POST['password']);
    if (!$_POST['username'] | !$_POST['password']) {
        echo ("<SCRIPT LANGUAGE='JavaScript'>
            window.alert('You did not complete all of the required fields')
            window.location.href='form1.html'
        </SCRIPT>");
        exit();
    }
    $sql= mysqli_query("SELECT * 
                        FROM `account` 
                        WHERE username = $username 
                        AND password = $password ");
    if(mysqli_num_rows($sql) > 0) {
        echo ("<SCRIPT LANGUAGE='JavaScript'>
            window.alert('Login Succesfully!.')
            window.location.href='form1.html'
        </SCRIPT>");
        exit();
    }else{
        echo ("<SCRIPT LANGUAGE='JavaScript'>
            window.alert('Wrong username or password. Please re-enter.')
            window.location.href='form1.html'
        </SCRIPT>");
        exit();
    }
}else{
}
?>

I think there is something wrong with the PHP coding since I keep on getting the ‘wrong username and password’ message.

UPDATE: screenshot of my database https://imgur.com/a/wPWdHDc

2

Answers


  1. I think

    "SELECT * FROM account WHERE username = $username AND password = $password "

    should be

    "SELECT * FROM account WHERE username = "$username" AND password ="$password""

    Login or Signup to reply.
  2. As quick fix, put quotes around the username and password variables :

    SELECT * FROM `account` WHERE username = '$username' AND password = '$password'
    

    Some tips to improve this code :

    • use prepared statements to avoid SQL injections
    • don’t store password in plain text, hash it (with a salt)

    Also, you have an error in your first condition, you use | which is a bitwise operator, instead of || which is the logical OR operator

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search