0

I'm trying to create a better code to update user info once they're on a user settings page, but only if that value is not None.

Essentially, turning this:

    if bool(request.form.get('username')) == True:
        cur.execute('UPDATE accounts SET username=%s WHERE id=%s', (request.form.get('username'), account['id']))

    if bool(request.form.get('password')) == True:
        cur.execute('UPDATE accounts SET password=%s WHERE id=%s', (sha256_crypt.hash(request.form.get('password')), account['id']))

    if bool(request.form.get('firstname')) == True:
        cur.execute('UPDATE accounts SET firstname=%s WHERE id=%s', (request.form.get('firstname'), account['id']))

    if bool(request.form.get('lastname')) == True:
        cur.execute('UPDATE accounts SET lastname=%s WHERE id=%s', (request.form.get('lastname'), account['id']))

To this:

    cur.execute('SELECT * FROM accounts WHERE username = %s', (username,))
    account = cur.fetchone()
    
    if request.method == 'POST':
        if request.form['submitbtn'] == 'update':
            form = request.form.to_dict()

            for x, y in form.items():
                if x == 'submitbtn':
                    print("it detected submit")
                    continue

                if y:
                    column = x
                    data = y
                    print("%s + %s" % (column, data))
                    cur.execute("UPDATE accounts SET %s = %s WHERE id = %s", (column, data, account['id']))

Unfortunately, the string is displayed in single 'quotes', so MySQL gives a syntax error: mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''firstname' = 'new_first_name' WHERE id = 6' at line 1

Any suggestions? Thank you

nau
  • 3
  • 2

0 Answers0