node_save not updating properly

By: Michael Phipps

29 Nov 2009

If you're doing bulk updates in drupal, and node_save doesn't seem to be working properly, this might be the problem

This issue is best described using a scenario.

I wanted to update a bunch of nodes with images after they had been created, so I wrote some code to cycle through the nodes, and update them with the images, however, when there were multiple images for a single node, only the last image change of each loop was being kept.

The problem wasn't in the saving of the node, it was actually in the loading of the node

While most people generally call node_load() with one parameter, a node id (nid), the node_load() function actually has 3 parameters.
The third one is $reset : Whether to reset the internal node_load cache. By default, the cache is not reset, so when you loop, and load a node again, even though you have saved a change to the node, that change is not yet available in the cache

So the trick when you load the node is:

$node = node_load($nid, NULL, TRUE);