What are the best practices for combining and summarizing MySQL data records in PHP?

When combining and summarizing MySQL data records in PHP, it is best practice to use SQL queries to retrieve the necessary data and then process it in PHP to create the desired summary. This can involve using functions like SUM(), COUNT(), AVG(), etc., to aggregate data as needed. It is also important to properly sanitize user input to prevent SQL injection attacks.

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

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve and summarize data
$sql = "SELECT SUM(column_name) AS total_sum FROM table_name WHERE condition";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Total Sum: " . $row["total_sum"];
    }
} else {
    echo "0 results";
}

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