Search code examples
phpdrupaldrupal-7

Drupal count of nodes by type and date?


I am trying to display the total count of one day for a specific node type"

function bootstrap_subtheme_get_node_count($content_type) {
     $time = strtotime('yesterday midnight');
     $query = "SELECT COUNT(*) amount FROM {node} n ".
            "WHERE n.type = :type and n.created => " . $time;
     $result = db_query($query, array(':type' => $content_type))->fetch();
     return $result->amount;
}

and to print

<?php bootstrap_subtheme_get_node_count('page'); ?>

Please correct me what I am doing wrong?


Solution

  • your code looks good, please make 2 changes

    1: change created as you done with type.

    2: remove * symbol from count(*) and put nid or other column name as you like, it is good for query performance.

    Code example:

    function bootstrap_subtheme_get_node_count($content_type) {
         $time = strtotime('yesterday midnight');
         $query = "SELECT COUNT(nid) amount FROM {node} n ".
                  "WHERE n.type = :type and n.created => :created";
         $result = db_query($query, array(':type' => $content_type,
                                          ':created' => $time))->fetch();
         return $result->amount;
    }