Can you provide an example of using PDO prepared statements to prevent SQL injection?

Responsive Ad Header

Question

Grade: Education Subject: Support
Can you provide an example of using PDO prepared statements to prevent SQL injection?
Asked by:
85 Viewed 85 Answers
Responsive Ad After Question

Answer (85)

Best Answer
(450)
```php prepare('SELECT * FROM users WHERE username = ? AND password = ?'); $stmt->execute([$_POST['username'], $_POST['password']]); $user = $stmt->fetch(); ?> ``` This example uses placeholders `?` in the SQL query, and the values are passed as an array to the `execute()` method. PDO handles the escaping and sanitization automatically.