Course contentsShow
← Security
Lesson 1237 of 3,05225. Application Security - Secure CodingFree lesson

Parameterized Queries and Prepared Statements

Master prepared statements across languages (PHP, Python, Java, .NET) with proper parameter binding and common implementation mistakes.

Parameterized Queries and Prepared Statements

What you'll learn: How to implement parameterized queries correctly across different programming languages to prevent SQL injection.

The Core Idea

Parameterized queries (also called prepared statements) separate your SQL code from user data by using placeholders. Think of it like a Mad Libs game: you write a sentence structure with blanks, and the user fills in the blanks—but they can't change the sentence itself, only fill the designated spots.

This prevents SQL injection because user input is never interpreted as SQL code—it's always treated as pure data, even if it contains SQL keywords or special characters.

Implementation Across Languages

PHP (PDO)

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $userEmail]);

Python (with psycopg2)

cursor.execute("SELECT * FROM users WHERE email = %s", (user_email,))

Java (JDBC)

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
stmt.setString(1, userEmail);

.NET (C#)

SqlCommand cmd = new SqlCommand("SELECT * FROM users WHERE email = @email", conn);
cmd.Parameters.AddWithValue("@email", userEmail);

Common Mistakes to Avoid

  1. String concatenation disguised as parameterization: Building the SQL string with user input first, then "preparing" it
  2. Using parameters for table/column names: Parameters only work for values, not SQL structure
  3. Mixing approaches: Combining safe parameters with unsafe string concatenation in the same query
  4. Wrong parameter binding: Using string formatting (%, f-strings) instead of the database library's parameter mechanism

Key Takeaway: Always use your database library's native parameterization (:name, ?, %s, @param) with proper binding—never concatenate user input into SQL strings, even when using prepared statements.