why my else cannoot execute while the statement is else?

Viewed 52

I want to create a login page script with the username and password as the data account from db. n then when my input is doesn't match the else didn't execute while username and password is did not exist in db. so what should i do to fix this. any somebody help me please

def logindb():
print ("=="*15+"\nPlease insert your username and password.")
username = input ("Username : ")
password = input ("Password : ")
cursor.execute(f"SELECT * FROM data WHERE username='{username}' and password='{password}'")
result = cursor.fetchall()
for i in result:
    if (i[0]) == username and (i[1]) == password:
        print ("=="*15+"\n\tLogin Success.\n"+"=="*15)
    else:
        print ("=="*15+"\nUsername or password is wrong.\n"+"=="*15)
3 Answers

Try changing:

cursor.execute(f"SELECT * FROM data WHERE username='{username}' and password='{password}'")

To:

cursor.execute(f"SELECT username, password FROM data WHERE username='{username}' and password='{password}'")

You're selecting ALL* columns, and if your 0 index column is not username, and your 1 index column is not password, your query result will not match up your submitted username and password.

if (i[0]) == username and (i[1]) == password:

It's also not a good idea to run your SELECT statements wide open if you don't need to. Retrieve only the columns explicitly that you need to retrieve.

You should really use a parameterized query.

But if you are going to use this method of data retrieval then I would go one step further then Griv's answer

cursor.execute(f"SELECT userid FROM data WHERE username='{username}' and password='{password}'")

I would never fetch the username or password. Instead, check for its existence by fetching the primary key of the table.

Then check if that value is null or not.

I am not familiar with python, I assume the f"SELECT is not a typo

In your code snippet, the statement can NEVER be else!

You query for a database entries matching username and password. For every entry (with the matching username and password) you again check if these credentials are correct.

I guess what you want, is to check if there are records found.

Something like this:

result = cursor.fetchall()
if (len(result) > 0):
    print ("=="*15+"\n\tLogin Success.\n"+"=="*15)
else:
    print ("=="*15+"\nUsername or password is wrong.\n"+"=="*15)

Side note: you really should hash the password instead of saving it as plain text in the database.

Related