I'm trying to create a user registration page using Flask, MySQL and HTML forms. I'm running into this error when I try to post data from the form to the database. Can anyone see where I might have gone wrong with the SQL?
The full error received is:
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 '%s' at line 1
My connection function is:
import mysql.connector
from flask import *
def connection():
conn = mysql.connector.connect(host="localhost", db="user_login",user="root",
password="password")
c = conn.cursor()
return c, conn
This is imported in the init.py file and called below:
class RegistrationForm(Form):
firstName = StringField('First Name', [validators.Length(min = 3, max = 25)])
lastName = StringField('Surname', [validators.Length(min = 3, max = 25)])
username = StringField('Username', [validators.Length(min = 4, max = 25)])
email = StringField('Email Address', [validators.Length(min = 6, max = 50)])
password = PasswordField('Password', [validators.required(),
validators.EqualTo('confirm', message = 'Passwords must match')])
confirm = PasswordField('Repeat Password')
@app.route('/register/', methods = ['GET', 'POST'])
def register_page():
try:
form = RegistrationForm(request.form)
if request.method == "POST" and form.validate():
firstName = form.firstName.data
lastName = form.lastName.data
username = form.username.data
email = form.email.data
password = form.password.data
is_admin = 0
c, conn = connection()
x = c.execute("SELECT * FROM users WHERE username = %s",(username))
if int(x) > 0:
flash("That username is already taken, please choose another")
return render_template('register.html', form = form)
else:
c.execute("""
INSERT INTO users (firstName, lastName, username, email, password, is_admin)
VALUES (%s, %s, %s, %s, %s, %s)
""",(firstName, lastName, username, email, password, is_admin))
conn.commit()
flash("Thanks for registering!")
c.close()
conn.close()
gc.collect()
session['logged_in'] = True
session['username'] = username
return redirect(url_for('dashboard'))
return render_template('register.html', form = form)
except Exception as e:
return(str(e))
I think your issue is the SELECT
, not the INSERT
. You are passing (username)
as a parameter -- this is not a tuple. You need to use a trailing comma:
x = c.execute("SELECT * FROM users WHERE username = %s", (username,))