Prepared Statements (Stop SQL Injection)
Learn prepared statements with real examples for SELECT and INSERT, and understand why they are safer.
SQL injection happens when user input becomes part of your SQL query.
Prepared statements separate: - SQL structure - user values
This is the safest standard.
Bad example (do NOT do this)
```php $email = $_POST['email']; $sql = "SELECT * FROM users WHERE email = '$email'"; ```
If attacker sends special input, the query can be manipulated.
Good example (prepared statement)
```php $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email"); $stmt->execute(["email" => $email]); $user = $stmt->fetch(); ```
Insert example
```php $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)"); $stmt->execute([ "name" => $name, "email" => $email ]); ```
Visual: why prepared is safer
```mermaid flowchart TD A[SQL Template] --> B[Prepared Statement] C[User Input] --> B B --> D[Database executes safely] ```
> Next: CRUD, build Create/Read/Update/Delete the right way.