Skip to content
PHP Logo

How can one efficiently handle sorting by multiple columns in a MySQL query in PHP?

When sorting by multiple columns in a MySQL query in PHP, you can use the ORDER BY clause with multiple columns separated by commas. Make sure to specify the sorting order (ASC for ascending, DESC for descending) for each column. This allows you to efficiently sort the results based on multiple criteria.

php
$query = "SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC";
$result = mysqli_query($connection, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Process the sorted data here
    }
} else {
    echo "Error: " . mysqli_error($connection);
}