The 'GROUP BY' statement in SQL is used to group rows based on one or more columns. It's often used with aggregate functions (SUM, COUNT, AVG, etc.) to perform calculations on groups of data.

In PHP, you can use the 'GROUP BY' statement in SQL queries by concatenating it with the rest of the query string. Here's an example:

$sql = "SELECT column1, column2, SUM(column3) as total
        FROM table_name
        GROUP BY column1, column2";

This query selects column1, column2, and the sum of column3 from the table_name table. The results are grouped by column1 and column2.

Once you've constructed your query string, you can execute it using a database connection and fetch the results. Here's an example using PDO:

$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

Here, $sql is the query string, executed using a PDO connection ($pdo). The results are fetched using the fetchAll method and stored in the $results variable.

You can then loop through the $results variable to access each row of data:

foreach ($results as $row) {
    echo $row['column1'] . " - " . $row['column2'] . " - " . $row['total'] . "<br>";
}

In this example, the values of column1, column2, and total are accessed using the associative array syntax ($row['column1'], $row['column2'], $row['total']).

Remember, the actual column names and table name in your query will depend on your specific database schema.

PHP SQL GROUP BY: Grouping Data and Performing Calculations

原文地址: https://www.cveoy.top/t/topic/dsa3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录