What are some best practices for validating user input when rearranging table columns in PHP?

When allowing users to rearrange table columns in PHP, it is important to validate the user input to prevent potential security risks such as SQL injection attacks. One way to validate user input is to ensure that the column names provided by the user match the expected column names in the database table. Additionally, you can sanitize the input to remove any potentially harmful characters.

// Validate user input for rearranging table columns
$userInput = $_POST['column_names'];

// Define an array of expected column names
$expectedColumns = ['column1', 'column2', 'column3'];

// Check if the user input matches the expected column names
foreach ($userInput as $column) {
    if (!in_array($column, $expectedColumns)) {
        // Handle invalid input
        die('Invalid column name detected');
    }
}

// Sanitize the input to remove any potentially harmful characters
$sanitizedColumns = array_map('htmlspecialchars', $userInput);

// Proceed with rearranging table columns using $sanitizedColumns