How can the FIND_IN_SET function be used to sort query results based on user selections in PHP?

When users make selections in a web application, we may need to sort query results based on those selections. The FIND_IN_SET function in MySQL can be used to achieve this by sorting the results based on the order of values specified by the user. In PHP, we can dynamically generate the ORDER BY clause using the FIND_IN_SET function with the user selections to sort the query results accordingly.

// Assuming $userSelections is an array of user selections
$userSelections = ['value1', 'value2', 'value3'];

// Generate the ORDER BY clause using FIND_IN_SET function
$orderClause = "FIND_IN_SET(column_name, '" . implode(',', $userSelections) . "')";

// Run the query with the dynamically generated ORDER BY clause
$query = "SELECT * FROM table_name ORDER BY $orderClause";
$result = mysqli_query($connection, $query);

// Fetch and display the sorted results
while ($row = mysqli_fetch_assoc($result)) {
    // Display the query results
}