tags:

Recently, I had to make mass changes to nodes while adding a new feature to a live website.

In one case, I wanted to add a date field to a content type with hundreds of existing nodes. For the sake of simplicity, best date that could be used for this field was the created date of the node. With that information, I was able to write the following script to replace any empty date fields with the created date.

<?php
  $sql
= "SELECT n.nid
          FROM {node} n
          WHERE n.type = 'my_content_type'
          ORDER BY n.nid DESC"
;
 
$result = db_query($sql);

 
$processed_nodes = 0;

  while(
$anode = db_fetch_object($result)) {
   
$bnode = node_load($anode->nid);

    if (!
$bnode->field_date_published[0]['value']) {
     
$bnode->field_date_published[0]['value'] = date('Y-m-d',$bnode->created).'T00:00:00';
     
node_save($bnode);
     
$processed_nodes++;
    }

  }

  if(
$processed_nodes){
   
$message = $processed_nodes.' nodes were processed.';
  } else {
   
$message = 'No nodes were processed.';
  }

 
drupal_set_message($message);
?>

Just run the script once, and all nodes are updated. This can be used for a variety of other changes. I used it also for updating the values of a text field and adding taxonomy based on various properties of the node.

I found it was more convenient for me, who's primary specialty is theming, to use this PHP script as opposed to running a script directly in the database. I am much more familiar with PHP and manipulating an object than I am with MySQL and the database schema.