What are the risks of SQL injection in PHP and how can they be mitigated?

SQL injection in PHP can allow attackers to execute malicious SQL queries, potentially leading to data loss or unauthorized access. To mitigate this risk, developers should use prepared statements with parameterized queries to prevent user input from being directly concatenated into SQL queries.

// Mitigating SQL injection with prepared statements
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

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