0

The following query retrieves every reservation in the database, but I only want to get the reservations that the current user made. When I run the query in the mysql command line, it works. Why isn't this working in my app?

from flaskext.mysql import MySQL
from flask.ext.login import LoginManager
from flask_login import current_user

...

db = MySQL()
db.init_app(app)

...

cur = db.connect().cursor()
cur.execute("SELECT ReservationID FROM Reservation WHERE user_name=" + "'" + current_user + "';")
reservation_instance = cur.fetchall()
davidism
  • 121,510
  • 29
  • 395
  • 339
TheRunner565
  • 99
  • 1
  • 6
  • 1
    you should [properly parameterize your query](http://stackoverflow.com/a/775399/2733506) to prevent sql injection. try printing out current_user right before the query to make sure it is correct and doesn't have any spaces or anything in it. if that doesn't work mock out your app context and run that query – John Ruddell Oct 07 '15 at 17:34

1 Answers1

2

current_user is a User instance. You can't just add it to a string, you need to use it's username (assuming you called the attribute "username").

You are currently open to SQL injection attacks. Never try to insert parameters into a query string yourself. Always use parameterized queries, which lets the driver do the work of building, quote, and escape the query properly.

cur.execute('SELECT ReservationID FROM Reservation WHERE user_name=?', [current_user.username])

The placeholder character (I used ? in the example) depends on the driver. Consider using SQLAlchemy, which normalizes this sort of thing and is much more powerful. There is the Flask-SQLAlchemy to make integration with Flask easier as well.

davidism
  • 121,510
  • 29
  • 395
  • 339