What are the potential security risks associated with using raw SQL queries in PHP, and how can they be mitigated?

Using raw SQL queries in PHP can expose your application to SQL injection attacks, where malicious users can manipulate queries to access or modify data. To mitigate this risk, you should use prepared statements with parameterized queries, which separate SQL code from user input and prevent injection attacks.

// Establish a database connection
$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 results
$results = $stmt->fetchAll();