views:

58

answers:

1

I currently use the statistics module (core) on my Drupal 6 install. This increments a count in the {node_counter} table every time the node is viewed, and this works.

My question is - can I programmatically increment this counter as well? I am looking to achieve this when users interact with content created from views (say click a lightbox), so being able to update the table with AJAX would be ideal.

I have done a quick search on d.o and there doesn't appear to be any modules that stick out straight away. Does anyone have any experience with this?

+4  A: 

It shouldn't be hard to make a custom module for this.

The query that the statistics module runs is:

db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), arg(1));
  // If we affected 0 rows, this is the first time viewing the node.
  if (!db_affected_rows()) {
    // We must create a new row to store counters for the new node.
    db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 1, 1, %d)', arg(1), time());

The only thing we need to do, is to replace arg(1) with the node id we want to add a count to this could be done in a custom module something like this.

function custom_module_menu() {
  $items['custom/ajax/%node'] = array(
    'title' => 'Update count',
    'page callback' => 'custom_module_update_counter',
    'page arguments' => array(2),
    'access callback' => array('custom_module_access_control'),
  );

 function custom_module_update_counter($node) {
   db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), $node->nid);
    // If we affected 0 rows, this is the first time viewing the node.
    if (!db_affected_rows()) {
      // We must create a new row to store counters for the new node.
      db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 1, 1, %d)', $node->nid, time());
 }

All that's left is to implement a custom access control function, you can check if the request is ajax or make whatever control you like, the function must just return TRUE or FALSE. You also need to make a ajax event with the node id in your setting, but that shouldn't be too hard either.

You need to hit the url custom/ajax/2 to update node with id 2 etc.

googletorp
Thankyou very much for your detailed answer. Will get cracking on the custom module.
wiifm
My module is now available for download on d.o http://drupal.org/project/statistics_ajax - in case anyone else needs similar functionality
wiifm