0% complete

PHP & MySQL · Lesson 10 of 11

Prepared Statements

Separate SQL structure from values to prevent injection.

Lesson

Prepared statements keep user-supplied values separate from SQL syntax. Use placeholders for every dynamic value; placeholders cannot stand in for table names or SQL keywords, so allowlist any dynamic identifier. Parameterization is the core defense against SQL injection for values. The PDO example binds a search term without concatenating it into the query string. Further guidance Use migrations to version schema changes, constraints to protect relationships, and prepared statements for every dynamic value. Scope writes with a precise condition, check affected rows, and use transactions when multiple statements must succeed together. Store credentials outside source control. Practice task: Create a fresh example for Prepared Statements. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Prepared Statements
PHP
$statement = $pdo->prepare('SELECT id FROM users WHERE email = :email');
$statement->execute(['email' => $email]);
$user = $statement->fetch(PDO::FETCH_ASSOC);
Expected output
A matching row or false when no row exists

Key points

  • Separate SQL structure from values to prevent injection.
  • Use prepared statements for values and constraints for data integrity.
  • Scope writes carefully and verify their result.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.