0

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

some_programmer
  • 3,268
  • 4
  • 24
  • 59
Callum
  • 195
  • 2
  • 22
  • Properly formatting your code will make it a lot easier to read... – Shawn Jul 07 '19 at 10:02
  • You should look up the precedence of `AND` and `OR`... and why do you just have the string `'no'` in there? That's always going to be false because when cast to a number it becomes `0`. What's the point? – Shawn Jul 07 '19 at 10:08
  • I tried changing it to use the numbers 1 and 2 (instead of yes and no) and got the same result – Callum Jul 08 '19 at 11:31

1 Answers1

1

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')
J_H
  • 17,926
  • 4
  • 24
  • 44
  • This worked thanks. So I assume when using a WHERE statement I shouldn't put = variable OR variable. I should use the in statement and then put the variables inside brackets – Callum Jul 08 '19 at 11:35