2
@app.route('/select/<username>')
def select(username):

    db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )

    cursor = db.cursor()

    cursor.execute("SELECT * FROM p_shahr")

    data = cursor.fetchall()

    db.close()

    return render_template('select.html', data=data)

I want to edit the select query in this script in order to have

SELECT * FROm p_shahr WHERE os = username

How should I edit the query to include the where clause above to set os to username that is coming from URL?

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
niloofar
  • 2,244
  • 5
  • 23
  • 44

1 Answers1

9

Use placeholders in the query and pass the parameters as a tuple to execute.

@app.route('/select/<username>')
def select(username):

    db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" )

    cursor = db.cursor()

    query_string = "SELECT * FROM p_shahr WHERE os = %s"
    cursor.execute(query_string, (username,))

    data = cursor.fetchall()

    db.close()

    return render_template('select.html', data=data)

But, be aware that this [passing data from URL directly to DB] is a very naive and attack prone approach. See

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64