What potential security risks are present when directly inserting external variables into SQL queries in PHP?

When directly inserting external variables into SQL queries in PHP, there is a risk of SQL injection attacks where malicious code can be injected into the query, potentially leading to unauthorized access or data manipulation. To prevent this, it is important to use prepared statements with parameterized queries in PHP, which helps to separate the SQL logic from the user input, thus mitigating the risk of SQL injection.

// Using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");

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

// Bind parameters
$stmt->bindParam(':username', $username);

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

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