How can developers prevent SQL injection attacks in PHP scripts, especially when dealing with user input?

SQL injection attacks can be prevented in PHP scripts by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL code from the user input, making it impossible for attackers to inject malicious SQL code. By using prepared statements, developers can ensure that user input is properly sanitized and secure.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the parameter
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();