Skip to content
PHP Logo

Are there any specific PHP functions or techniques recommended for preventing SQL injection attacks?

SQL injection attacks can be prevented in PHP by using prepared statements with parameterized queries. This technique allows the database to distinguish between the SQL code and the data being input, effectively preventing malicious SQL code from being executed. By using prepared statements, you can ensure that user input is treated as data rather than executable code.

php
// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();