0

How exactly do you check if a table contains a specific value? For example,

if request.method == 'POST':
        email = request.form.get("email")
        cur = mysql.connection.cursor()
        cur.execute("SELECT * from login_info")
        data = cur.fetchall()    
        if email == data: # <--- I don''t know. This is what I want to know```
emergenitro
  • 1
  • 1
  • 2

1 Answers1

0

The data variable here will return a tuple from the cur.fetchall() function which will look something like this

((1,'random_email1@mail.com','First_name1','Last_name1'), 
 (2,'random_email2@mail.com','First_name2','Last_name2'),
 (3,'random_email3@mail.com','First_name3','Last_name3')...)

If you need to find a row with a specific email address I suggest you do this for you SQL command

email_query = "SELECT * FROM login_info WHERE email = %s"
values = (email)
cur.execute(email_query, values)
data = cur.fetchone()
#Assuming that there will be only one Row with the E-mail ID as the PRIMARY KEY

The data tuple will then only contain a single row from the SQL table as follows (1,'random_email1@mail.com','First_name','Last_name')

Here you can simply fetch the email address value by using data[1] which is where the email is in the tuple.

C Rishi
  • 216
  • 1
  • 5
  • I understood the logic behind it but I'm getting the following error: `ProgrammingError: not all arguments converted during string formatting` in the line `cur.execute(email_query, values)` I don't understand this, I tried all fixes – emergenitro May 16 '21 at 13:05
  • Oh, that problem is a classic one, you have to make sure that the variable `email` holds a string and not a list or a tuple holding a string. To make sure, just do `print(type(email))` – C Rishi May 16 '21 at 16:10
  • Hmm, I'm getting the output as string.. For all the arguments (values, email_query and even email). So, I'm not exactly sure where it's going wrong, any idea? Oh wait, is it possible that it's because the first column of the db is id (an integer)? – emergenitro May 16 '21 at 22:51
  • No, that shouldn't be a problem, as that is something that is returned as a response which will be a tuple. I think trying to follow this example from the official docs might help you [MySQL Connector example](https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html) – C Rishi May 17 '21 at 20:10
  • Alright, thanks a ton! I got it working :D – emergenitro May 20 '21 at 12:26