LOGBOOK

HELP

Quiz Entry - updated: 2026.06.20

How do you write a prepared statement to prevent SQL injection?

Use parameterized (prepared) queries: the SQL structure is compiled first, then user data is bound as parameters that can never run as code.

Java (JDBC):

String query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);  // Bound as data, never as SQL
stmt.setString(2, passwordHash);
ResultSet rs = stmt.executeQuery();

PHP (PDO):

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

Why it works: The ? or :user placeholders tell the DB engine "this is data, not code." Even if username contains ' OR 1=1--, it's treated as a literal string, not SQL.

Common mistake: String concatenation like "SELECT * FROM users WHERE name = '" + input + "'" — this mixes code and data, enabling injection.

From Quiz: SPRG / Input Validation & Output Encoding | Updated: Jun 20, 2026