How can I add taxonomy terms programatically into Drupal via an CSV file? Part 2

Hello Experts,

This is actually a continuation of the following question:
http://www.experts-exchange.com/Software/Server_Software/Content_Management/WebBased_CMS/Drupal/Q_26878149.html

I have a CSV file (attached) and each row contains THE FOLLOWING:
VOCABULARY_NAME,TERM_NAME,TERM_WEIGHT,TERM_PARENT
I'm using HOOK_UPDATE_N so that when we run "update.php" it will see the update and add the vocabularies and their corresponding terms programatically.
Basically I want to loop through each row in the CSV file and do the following:
-add the vocabulary if it doesn't exist
-retrieve the ID of the newly added or existing vocabulary
-add the term along with its corresonding vocabulary and weight
-retrieve the ID of the newly added term
-retrieve the ID of the term parent
-add the term ID and the parent term ID to the term_hierchy table
When I run update.php the vocabularies get added with no problem but the rest of the code fails. I'm guessing it has something to do with how I'm trying to retrieve the ID numbers of the newly added data.  I'm trying to add all of this data dynamically without having to loop through this csv file more than once.  Any ideas would be greatly appreciated.
Thanks in advance
/**
 * Update to programatically add taxonomies
 */
function my_custom_module_update_6001() {
	$ret = array();
	$file = file_directory_path()."/smallbiz_taxonomies2.csv";
	if(file_exists($file)){
			$theOpenFile = fopen($file,"r");
			if($theOpenFile){
					//loop through each line in the CSV file
					while(!feof($theOpenFile)){
					//convert each line to an array
					$theRowContents = fgetcsv($theOpenFile);
					//create easy to use names from the array
					$theVocabularyName = $theRowContents[0];
					$theTermName = $theRowContents[1];
					$theTermWeight = $theRowContents[2];
					$theTermParent = $theRowContents[3];
					//Check to see if the vocabulary already exists
					$theVocabularyNameCount = db_result(db_query("SELECT COUNT(name) FROM {vocabulary} WHERE name = '%s'",$theVocabularyName));
						//Add the vocabulary if it doesn't exist
						if($theVocabularyNameCount == 0){
						$ret[] = db_query("INSERT INTO {vocabulary} (name,relations,hierarchy,multiple,required,weight) VALUES ('%s',1,1,1,1,0)",$theVocabularyName);
						}
						//Get the ID of the vocabulary
						$theVocabularyId = db_result(db_query("SELECT vid FROM {vocabulary} WHERE name = '%s'",$theVocabularyName));
						//Add the new TERM to the database
						$ret[] = db_query("INSERT INTO {term_data} (vid,name,weight) VALUES (%d,'%s',%d)",$theVocabularyId,$theTermName,$theTermWeight);	
						//Get the ID of the new TERM we just added
						$theTermId = db_result(db_query("SELECT tid FROM {term_data} WHERE name = '%s' AND vid = %d",$theTermName,$theVocabularyId));
						//If the value of $theTermParent equals "none", then add the TERM to the TERM_HIERARCHY table with a parent of 0
						if($theTermParent == "none"){
						$ret[] = db_query("INSERT INTO {term_hierarchy} (tid,parent) VALUES (%d,0)",$theTermId);	
						}else{
						//If the value of $theTermParent does not equal "none", go get the ID of the term so we can add the new term with the right parent ID
						$theParentId = db_result(db_query("SELECT tid FROM {term_data} WHERE name = '%s' AND vid = %d",$theTermParent,$theVocabularyId));
						$ret[] = db_query("INSERT INTO {term_hierarchy} (tid,parent) VALUES (%d,%d)",$theTermId,$theParentId);	
						}
					}
			}
			fclose($theOpenFile);
	}
  return $ret;
}

Open in new window

smallbiz-taxonomies2.csv
LVL 1
xamianAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

xamianAuthor Commented:
OK I have a slight revision to make.  The code I submitted above actually works.  It's adding the taxonomy terms perfectly, but when I run update.php I'm getting a failure message for each line in the csv file.  The problem is that it's not telling me what went wrong.  The message towards the top says that the errors were logged but when I go to the log (/admin/reports/dblog) nothing is there.  After scouring the internet I think the problem is that I'm not using the WATCHDOG() function to log the errors but I can't find any examples of how I would use watchdog in a hook_update_n function.  If anyone has any ideas as to how I would do this it would be greatly appreciated.
Thanks
0
junipllcCommented:
This might help:

http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/watchdog/6

However, note the limitation for scopes where a full Drupal system isn't loaded. Is this Drupal 6? If it's 7 that won't matter.

Also, is this an ongoing task that you want to perform, or is it just a one-time thing? Although I didn't really get to the nitty-gritty of your code (late night) have you considered using hook_cron instead of hook_update_n? In that case you should just be able to do something like this:

$returnvalue = do_something_that_might_cause_an_error()
watchdog('my_custom_module_update_6001', $returnvalue);  // the first value doesn't matter, make it whatever you want

Open in new window


or even use a try/catch structure:

http://stackoverflow.com/questions/933081/try-catch-statements-in-php

and use the exception to generate the error.

Just food for thought, I haven't had to do what you're doing, but I'm sure there are several ways of doing it, and making it work ;)

Good luck, and let us know if you are still having trouble (even after my babble above!)

Mike
0
xamianAuthor Commented:
Hi Mike,
I actually found the solution myself some time ago and forgot to update this.  As I mentioned in my post the code I was using in hook_update technically worked but drupal kept telling me there were failures.  It turned out that for some reason that I still can't explain Drupal did not like me using the db_query function to INSERT INTO the TERM_DATA and VOCABULARY tables.  It had no problems with SELECT, UPDATE or any other SQL function, it was just choking on the INSERT INTO's.  It wasn't until I used the TAXONOMY_SAVE_VOCABULARY and TAXONOMY_SAVE TERM functions that I could get it to work without errors.  I've attached the working code just in case someone else my need to do the same thing.
/**
 * Update to programatically add taxonomies
 */
function my_movies_update_6001() {
  $ret = array();


	$file = file_directory_path()."/my_custom_taxonomies.csv";
	if(file_exists($file)){
			$theOpenFile = fopen($file,"r");
			if($theOpenFile){
					while(!feof($theOpenFile)){
					
					$theRowContents = fgetcsv($theOpenFile);
					$theVocabularyName = $theRowContents[0];
					$theTermName = $theRowContents[1];
					$theTermWeight = $theRowContents[2];
					$theTermParent = $theRowContents[3];
					
					$theVocabularyNameCount = db_result(db_query("SELECT COUNT(name) FROM {vocabulary} WHERE name = '%s'",$theVocabularyName));
					
						//add vocabulary -START
						if($theVocabularyNameCount == 0){
							 $vocabulary = array(    
								 'name' => t($theVocabularyName),    
								 'multiple' => 1,    
								 'required' => 1,    
								 'hierarchy' => 1,    
								 'relations' => 1,    
								 'weight' => -10,    
								 'nodes' => array('smallbiz_service_description' => 1),
							   );  
						   taxonomy_save_vocabulary($vocabulary);
						}
						//add vocabulary -END
					$theVocabularyId = db_result(db_query("SELECT vid FROM {vocabulary} WHERE name = '%s'",$theVocabularyName));
					
					  $term = array(
					  'vid' => $theVocabularyId, 
					  'name' => $theTermName);  
					  taxonomy_save_term($term);
					  
					$theTermId = db_result(db_query("SELECT tid FROM {term_data} WHERE name = '%s' AND vid = %d",$theTermName,$theVocabularyId));
					
						if($theTermParent != "none"){
						$theParentId = db_result(db_query("SELECT tid FROM {term_data} WHERE name = '%s' AND vid = %d",$theTermParent,$theVocabularyId));
					 $term = array(
					 'tid' => $theTermId,
					  'vid' => $theVocabularyId, 
					  'name' => $theTermName,
					  'parent'=>$theParentId);  
					  taxonomy_save_term($term);
						}

					}
			}
			fclose($theOpenFile);  
	}
	
	
  return $ret;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
junipllcCommented:
Wow. Sorry then.
0
xamianAuthor Commented:
I'm giving myself the points becuase I'm the one who banged his head against the desk for three weeks trying to figure this out without any help from the Drupal or Experts-Exchange community.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Drupal

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.