What precautions should be taken when passing user input (such as column names) in PHP for sorting tables?

When passing user input for sorting tables in PHP, it is important to sanitize and validate the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries to safely pass user input to the database. Additionally, you can limit the allowed input values to a predefined set of options to avoid any unexpected behavior.

// Assuming $sort_column is the user input for column name
$allowed_columns = ['column1', 'column2', 'column3']; // Define allowed column names

if (in_array($sort_column, $allowed_columns)) {
    $stmt = $pdo->prepare("SELECT * FROM table_name ORDER BY $sort_column");
    $stmt->execute();
    // Fetch and display results
} else {
    echo "Invalid column name";
}