I have a module that programmatically adds a whole lot of nodes to my Drupal 7 site. To prevent duplicates I want to check whether the title of my newly created node doesn't already exist in the system. There will never be a case where two nodes have the same name. I've tried using node_load()
, but that doesn't seem to allow me to load nodes based on a title.
I'm stumped on how to proceed, so I was wondering if somebody here could help me.
To summarize: How do I check whether a node with a certain title already exists?
Thanks.
You could get all the node titles with a SQL query like:
$row = db_query('SELECT nid FROM {node} WHERE title = :mytitle', array(':mytitle' => $myNewTitle))->fetchField();
if(!isset($row['nid'])) {
//safe to continue
} else {
//that title is already there and its in node with node id "nid"
}
And if there are no results returned then you may assume you're good to go.
Or alternatively you could edit the node table to make the title field UNIQUE and handle the error thrown by MySQL. Don't really know how feasible that is though.