How can PHP be used to calculate the smallest and largest values in a column for date ranges?
To calculate the smallest and largest values in a column for date ranges in PHP, you can use SQL queries with the MIN() and MAX() functions to retrieve the desired values. You can specify the date range using a WHERE clause in the SQL query to filter the results.
// Connect to the 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);
}
// Define the date range
$start_date = '2022-01-01';
$end_date = '2022-12-31';
// Query to get the smallest value in the column for the date range
$sql_min = "SELECT MIN(column_name) AS min_value FROM table_name WHERE date_column BETWEEN '$start_date' AND '$end_date'";
$result_min = $conn->query($sql_min);
$row_min = $result_min->fetch_assoc();
$min_value = $row_min['min_value'];
// Query to get the largest value in the column for the date range
$sql_max = "SELECT MAX(column_name) AS max_value FROM table_name WHERE date_column BETWEEN '$start_date' AND '$end_date'";
$result_max = $conn->query($sql_max);
$row_max = $result_max->fetch_assoc();
$max_value = $row_max['max_value'];
// Display the smallest and largest values
echo "Smallest value: " . $min_value . "<br>";
echo "Largest value: " . $max_value;
// Close the connection
$conn->close();