What security risks are involved in directly inserting external data into MySQL queries in PHP, and how can they be mitigated using prepared statements?

Directly inserting external data into MySQL queries in PHP can lead to SQL injection attacks, where malicious code is injected into the query, potentially giving unauthorized access to the database. Prepared statements in PHP help mitigate this risk by separating the query logic from the data, preventing malicious code from being executed.

// Using prepared statements to mitigate SQL injection risk
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();