Drupal – Import data into nodes and content types
Importing data into Drupal can be a bit complicated because of node revisions. The trick is that the data needs to be inserted into the node and the node revisions tables, and the two need to reference each other. This becomes even more complicated when using custom content types which also need to reference these nodes.
The function insert_node() takes the node title, body, content type (such as ‘page’ or ‘event’), and optionally the date (as a unix timestamp). It uses two global variables for the ids so that you can reference the ‘nid’ and ‘vid’ values for the inserted rows in other functions, as illustrated in the example insert_special_node().
function insert_node($title, $type, $body, $date = '')
{
global $insert_id, $insert_revision_id; //nid and vid
if ($date == '')
{
$sql = 'INSERT INTO node (title, type, uid, created, changed) VALUES (\'' . $title . '\', \'' . $type . '\', 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())';
} else {
$sql = 'INSERT INTO node (title, type, uid, created, changed) VALUES (\'' . $title . '\', \'' . $type . '\', 1, ' . $date . ', ' . $date . ')';
}
$result = db_query($sql);
$insert_id = mysql_insert_id();
$sql = 'INSERT INTO node_revisions (nid, title, uid, body, teaser) VALUES (' . $insert_id . ', \'' . $title . '\', 1, \'' . $body . '\', \'' . $body . '\')';
$result = db_query($sql);
$insert_revision_id = mysql_insert_id();
if ($insert_id > 0)
{
$sql = 'UPDATE node SET vid = ' . $insert_revision_id . ' WHERE nid = ' . $insert_id;
$result = db_query($sql);
}
}
//example usage of insert_node with a sample content type called 'special'
function insert_special_node()
{
global $insert_id, $insert_revision_id; //nid and vid
$content_type = 'special';
//use mysql_real_escape_string() to clean user text for database insert
//this is mainly useful when inserting data read from another database query
$title = mysql_real_escape_string('title');
$body = mysql_real_escape_string('body text');
$special_text = mysql_real_escape_string('test');
insert_node($title, $content_type, $body);
$sql = 'INSERT INTO content_type_special (vid, nid, field_special_value) VALUES (' . $insert_revision_id . ', ' . $insert_id . ', \'' . $special_text . '\')';
$result = db_query($sql);
}
