What are the potential security risks associated with using user input directly in SQL queries, as demonstrated in the code example?

Using user input directly in SQL queries can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, it is important to 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 data.

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

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

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo $row['username'] . "<br>";
}