How can prepared statements and parameterized queries be utilized to prevent SQL injection attacks in PHP applications?

SQL injection attacks can be prevented in PHP applications by using prepared statements and parameterized queries. Prepared statements allow the database to distinguish between code and data, preventing malicious SQL code from being executed. Parameterized queries bind variables to placeholders in the SQL query, ensuring that user input is treated as data rather than executable code.

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

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

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

// Execute the prepared statement
$stmt->execute();

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