codegurukool.com · Free coding tutorials & online compiler

Home › SQL Tutorial › SQL injection and prepared statements

SQL injection and prepared statements

Keep attackers out of your queries.

SQL injection happens when user input is pasted into a query as text. Input like ' OR '1'='1 then changes the meaning of the query. The fix is parameterized (prepared) statements: the query is sent first with a ? placeholder, and the value is sent separately, so it is always treated as data, never as SQL.

Example code

-- UNSAFE: query built by joining strings
-- "SELECT * FROM Customers WHERE name = '" + input + "'"

-- SAFE: prepared statement
PREPARE stmt FROM 'SELECT * FROM Customers WHERE name = ?';
SET @n = ''' OR ''1''=''1';
EXECUTE stmt USING @n;

Run this code in the online editor

← SQL indexes, dates and viewsLive project: Mini shop database →