What potential security risks are present in the PHP code provided, and how can they be mitigated?

The potential security risk in the provided PHP code is the use of user input directly in the SQL query without proper sanitization, which can lead to SQL injection attacks. To mitigate this risk, you should use prepared statements with parameterized queries to separate the SQL logic from the user input.

// Original code with SQL injection vulnerability
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysqli_query($connection, $query);

// Mitigated code using prepared statements
$user_input = $_POST['username'];
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();
$result = $stmt->get_result();