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

Using user input directly in SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To mitigate this risk, you should always sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL query logic from the user input.

// Example of using prepared statements to mitigate SQL injection risk
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Sanitize and validate user input
$userInput = $_POST['user_input'];
$userInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);
$stmt->execute();

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

// Process results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}