Start learning free

LESSON 158 OF 188 · BACKEND: BACKEND WITH AI

The AI Pasted Text into SQL

Practice

An AI assistant wrote a product search for this shop: /products/search?q=te finds every product whose name contains te. It built the SQL with an f-string:

word = request.args.get("q", "")
rows = db.execute(f"SELECT name, price FROM products WHERE name LIKE '%{word}%'").fetchall()

The f-string pastes the visitor's text into the SQL itself. A quote in that text ends the SQL string early, and the rest runs as SQL: Ana's breaks the query, and x' UNION SELECT name, email FROM customers -- answers every customer's name and email, as if they were products. This is SQL injection.

The fix is a placeholder: write ? in the SQL and pass the value beside it, in a tuple. Here it is on another table:

rows = db.execute("SELECT name FROM customers WHERE city = ?", (city,)).fetchall()

The SQL text stays the same whatever the visitor types, and the database only compares the value, quotes and all. Your code must give these answers:

GET /products/search?q=te     →  200  [{"name": "Notebook", "price": 7}, {"name": "Teapot", "price": 22}]
GET /products/search?q=MUG    →  200  [{"name": "Mug", "price": 12}]
GET /products/search?q=Ana's  →  200  []
GET /products/search?q=x' UNION SELECT name, email FROM customers --  →  200  []
GET /products/search          →  200  [{"name": "Mug", "price": 12}, {"name": "Notebook", "price": 7}, … all 8 products]

Your task: rewrite search_products. Read q (default ""), build the pattern %word% as a Python string, run the query with LIKE ? and the pattern as its value, and answer the rows as a list of dictionaries.


Assignment
Follow the Coding Tutorial to rewrite search_products with a placeholder.


Hint
The % signs go into the Python value, not into the SQL: the SQL only says LIKE ?. Keep the comma in (pattern,): it makes a tuple with one item. dict(row) turns a row into a dictionary.


STEP 1 OF 7
    Ctrl + Enter to check