What are the recommended methods for preventing SQL injection in PHP applications, especially when dealing with user input for database queries?
SQL injection is a common attack where malicious SQL statements are inserted into an entry field for execution. To prevent SQL injection in PHP applications, it is recommended to use prepared statements with parameterized queries, input validation, and escaping user input before using it in a query.
// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();