How can data sorting be optimized in PHP when pulling data from a database?

When pulling data from a database in PHP, data sorting can be optimized by utilizing the ORDER BY clause in the SQL query. This allows the database to handle the sorting operation efficiently before returning the data to PHP. Additionally, using indexes on the columns being sorted can further improve the sorting performance.

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Query to retrieve data from the database sorted by a specific column
$sql = "SELECT * FROM table_name ORDER BY column_name";
$result = $conn->query($sql);

// Loop through the sorted data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Process the data
    }
} else {
    echo "0 results";
}

// Close the database connection
$conn->close();