All you have to do is make a query before insertion, and do a fetchone
. If fetchone
returns something, then you know for sure that there is a record already in the DB that has the email
OR username
:
def signup():
email = request.form['email']
username = request.form['user']
password = request.form['password']
# Create cursor object
cur = g.db.cursor()
# run a select query against the table to see if any record exists
# that has the email or username
cur.execute("""SELECT email
,username
FROM users
WHERE email=?
OR username=?""",
(email, username))
# Fetch one result from the query because it
# doesn't matter how many records are returned.
# If it returns just one result, then you know
# that a record already exists in the table.
# If no results are pulled from the query, then
# fetchone will return None.
result = cur.fetchone()
if result:
# Record already exists
# Do something that tells the user that email/user handle already exists
else:
cur.execute("INSERT INTO users VALUES (?, ?, ?)", (email, username, password))
g.db.commit()