How can PHP developers ensure that user input is properly sanitized and validated to prevent SQL injection attacks when working with database queries?

To prevent SQL injection attacks, PHP developers can sanitize and validate user input before using it in database queries. This can be achieved by using prepared statements with parameterized queries, escaping special characters, and using input validation functions to ensure the data meets expected criteria.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

while ($row = $stmt->fetch()) {
    // process results
}