What are the best practices for passing and handling column numbers as parameters in PHP when implementing expandable columns in a table?

When implementing expandable columns in a table in PHP, it is important to pass and handle column numbers as parameters in a secure and efficient manner. One best practice is to use integer values for column numbers to prevent SQL injection attacks. Additionally, it is recommended to validate the column number parameter to ensure it falls within the range of available columns in the table.

// Validate and sanitize the column number parameter
$column_number = isset($_GET['column']) ? intval($_GET['column']) : 0;

// Define an array of valid column numbers
$valid_columns = [0, 1, 2, 3]; // Assuming there are 4 columns in the table

// Check if the provided column number is valid
if (!in_array($column_number, $valid_columns)) {
    // Handle invalid column number, e.g. set a default column number
    $column_number = 0;
}

// Use the validated column number in your query or logic
$query = "SELECT * FROM table_name ORDER BY column_$column_number";
// Execute the query and display the results