How can PHP be used to calculate the difference between two values in a MySQL database, specifically for tracking monthly consumption data?
To calculate the difference between two values in a MySQL database for tracking monthly consumption data, you can retrieve the values from the database using SQL queries and then perform the calculation in PHP. Subtract the previous month's consumption value from the current month's consumption value to get the difference.
<?php
// 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 consumption values for current and previous month
$currentMonthQuery = "SELECT consumption FROM consumption_data WHERE month = 'current'";
$previousMonthQuery = "SELECT consumption FROM consumption_data WHERE month = 'previous'";
$currentMonthResult = $conn->query($currentMonthQuery);
$previousMonthResult = $conn->query($previousMonthQuery);
if ($currentMonthResult->num_rows > 0 && $previousMonthResult->num_rows > 0) {
$currentMonthData = $currentMonthResult->fetch_assoc();
$previousMonthData = $previousMonthResult->fetch_assoc();
// Calculate the difference
$difference = $currentMonthData['consumption'] - $previousMonthData['consumption'];
echo "Monthly consumption difference: " . $difference;
} else {
echo "Error: Unable to retrieve consumption data";
}
$conn->close();
?>