Home > Enterprise >  why my else cannoot execute while the statement is else?
why my else cannoot execute while the statement is else?

Time:09-16

my else didn't execute while username and password is wrong. 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)

CodePudding user response:

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.

CodePudding user response:

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

  • Related