How can PHP beginners avoid script errors when sorting data in SQL queries?

PHP beginners can avoid script errors when sorting data in SQL queries by properly sanitizing user input to prevent SQL injection attacks. They should also ensure that the SQL query syntax is correct and that the sorting column exists in the database table. Additionally, beginners should handle any potential errors that may occur during the execution of the SQL query to prevent script errors.

// Example of sorting data in SQL query with error handling
$sort_column = isset($_GET['sort']) ? $_GET['sort'] : 'default_column';
$sort_order = isset($_GET['order']) ? $_GET['order'] : 'ASC';

// Sanitize user input
$sort_column = filter_var($sort_column, FILTER_SANITIZE_STRING);
$sort_order = strtoupper($sort_order) === 'DESC' ? 'DESC' : 'ASC';

// Construct SQL query
$sql = "SELECT * FROM table_name ORDER BY $sort_column $sort_order";

// Execute SQL query with error handling
$result = mysqli_query($conn, $sql);
if (!$result) {
    die('Error executing query: ' . mysqli_error($conn));
}

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

// Free result and close connection
mysqli_free_result($result);
mysqli_close($conn);