What are the best practices for retrieving and storing user input from Select2 in PHP for further processing?

When retrieving and storing user input from Select2 in PHP for further processing, it is important to properly handle the data to prevent security vulnerabilities such as SQL injection. To do this, you should sanitize the input data using functions like htmlspecialchars() or mysqli_real_escape_string(). Additionally, you should validate the input to ensure it meets the expected format before storing it in a database or using it in any other way.

// Retrieve user input from Select2
$user_input = $_POST['select2_input'];

// Sanitize the input data
$sanitized_input = htmlspecialchars($user_input);

// Validate the input data
if (/* Add your validation logic here */) {
    // Store the input data in a database or use it for further processing
    // Example: $sql = "INSERT INTO table_name (column_name) VALUES ('$sanitized_input')";
} else {
    // Handle invalid input
}