What are the advantages of storing file counts in a database rather than counting them dynamically in PHP?

Storing file counts in a database rather than counting them dynamically in PHP can improve performance by reducing the need to scan directories and count files on each request. This approach also allows for easier management and tracking of file counts over time, as well as enabling more efficient querying and reporting on file statistics.

// Assuming a database table named 'file_counts' with columns 'id' and 'count'

// Update file count in database
$newCount = // logic to count files
$query = "UPDATE file_counts SET count = :count WHERE id = 1";
$stmt = $pdo->prepare($query);
$stmt->execute(['count' => $newCount]);

// Retrieve file count from database
$query = "SELECT count FROM file_counts WHERE id = 1";
$stmt = $pdo->query($query);
$fileCount = $stmt->fetchColumn();

echo "Total files: " . $fileCount;