Checking if a user has already voted, returns true even when they haven't?

87 Views Asked by At

The user enters their userid and then votes either 'yes' or 'no' but the code returns true and the if statement is executed even when the user hasn't voted.

For example - doing userid = 1 and voting, userid = 1 and voting. The second time userid tries to vote it does say you've already voted but if you then do userid = 2 for the third iteration it says you've already voted, which isn't true.

import sqlite3

conn = sqlite3.connect(":memory:")
cur = conn.cursor()

with conn:
    cur.execute("CREATE TABLE users(votes, userid INTEGER)")

for i in range(3):
    userid = input("Enter your user id: ")
    votes = input("Vote yes or no: ")
    with conn:
        cur.execute("SELECT * FROM users WHERE votes = 'yes' OR 'no' AND userid = ?", (userid,))
        user_voted = cur.fetchall()

        if user_voted:
            print("You have already voted")

        else:
            cur.execute("INSERT into users(userid, votes) VALUES(?, ?)", (userid, votes))
            print(cur.fetchall())

with conn:
    cur.execute("SELECT * FROM users")
    print(cur.fetchall())

There are no error messages, it just produces the wrong result

1

There are 1 best solutions below

1
J_H On

WHERE votes = 'yes' OR 'no'

If you don't want repeated mention of the votes column, then phrase it as:

WHERE votes in ('yes', 'no')