How should ASC and DESC be used in an SQL query in PHP without causing errors?

When using ASC or DESC in an SQL query in PHP, it is important to properly concatenate the sorting direction with the column name to avoid syntax errors. One way to do this is by using a conditional statement to dynamically add ASC or DESC based on user input or predefined logic.

// Example of using ASC or DESC in an SQL query in PHP without causing errors

$sortColumn = "name"; // Column to sort by
$sortDirection = "ASC"; // Sorting direction (ASC or DESC)

// Construct SQL query with proper sorting
$sql = "SELECT * FROM table_name ORDER BY $sortColumn $sortDirection";

// Execute the query and handle the results
$result = mysqli_query($connection, $sql);

// Process the result set
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Process each row
    }
} else {
    echo "No results found.";
}