What are potential security risks when using dynamic SQL queries in PHP?

When using dynamic 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 mitigate this risk, it is important to use prepared statements with parameterized queries instead of directly concatenating user input into the SQL query.

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