How can the use of prepared statements and parameterized queries in PHP help prevent SQL injection attacks when interacting with a MySQL database?

Using prepared statements and parameterized queries in PHP can help prevent SQL injection attacks by separating SQL code from user input. This means that user input is treated as data rather than executable code, making it impossible for malicious SQL code to be injected into the query.

// Connect to MySQL database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind the parameter value
$stmt->bindParam(':username', $_POST['username']);

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

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