What are the advantages of performing calculations and sorting directly in a database query rather than in PHP code?

Performing calculations and sorting directly in a database query can be more efficient and faster than doing it in PHP code. This is because databases are optimized for handling large amounts of data and can leverage indexes and query optimization techniques to process the data efficiently. By moving these operations to the database level, it can reduce the amount of data that needs to be transferred between the database and the PHP application, leading to better performance.

// Example of performing calculations and sorting directly in a database query

$query = "SELECT column1, column2, (column3 * 2) AS calculated_column
          FROM table
          WHERE condition
          ORDER BY column1";

$result = mysqli_query($connection, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Process the results
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}

mysqli_close($connection);