What is the best way to count and display the number of records in a database table based on a specific year using PHP?
To count and display the number of records in a database table based on a specific year using PHP, you can execute a SQL query that counts the number of records with a date column that falls within the specified year. You can then fetch the count result and display it on the webpage.
<?php
// Connect to 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);
}
// Specify the year
$year = 2022;
// SQL query to count records based on specific year
$sql = "SELECT COUNT(*) as count FROM table_name WHERE YEAR(date_column) = $year";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Number of records in $year: " . $row["count"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What is the role of interfaces in PHP and how can they be utilized to create more flexible and reusable code structures when working with multiple classes?
- What are the potential pitfalls of using PHP to include SVG code inline in a document?
- What potential issue is indicated by the error message "Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource" in the PHP code?