Skip to content

PHP vs SQL

PHP runs the application. SQL asks a relational database to read or change its data. In a PHP web app, PHP can check who may see a sales report, a SQL query can calculate the totals, and PHP can format those totals for the reader.

TaskPHPSQL
Handle a web requestRead input, apply permissions, and build the response.Run statements that the application sends to the database.
Group dataUse a loop for records already in application memory.Use GROUP BY to group records where they are stored.
Choose output orderExplicitly sort lists or map entries before presenting them.Use ORDER BY for a predictable row order.
Work with inputValidate a value and pass it using a bound parameter.Receive the parameter as data when the database executes the prepared statement.
<?php
$statuses = ['open', 'closed', 'open'];
$totals = array_count_values($statuses);
ksort($totals);
foreach ($totals as $status => $total) {
printf("%s|%d\n", $status, $total);
}
WITH tickets(status) AS (
VALUES ('open'), ('closed'), ('open')
)
SELECT status, COUNT(*) AS total
FROM tickets
GROUP BY status
ORDER BY status;

Run the PHP file with php tickets.php and the SQL file with sqlite3 :memory: < tickets.sql. With SQLite’s default list output format, both print closed|1 and then open|2. The SQL statement expresses the grouping directly. For a large table already in the database, grouping there can send fewer rows back to PHP.

Store tickets in SQLite and use SQL to query or group them. Keep the request, validation and display in PHP. Learn PDO prepared statements as soon as the database query starts receiving values from a form. Keep data validation and access checks even when you use a framework’s query builder.