I am trying to return all tags from a vocabulary but the code below keeps giving me error.

$vid = 1;  
$nid = arg(1);

$getterms = db_query('SELECT t.tid, t.* FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight', array(':vid' => $vid, ':node_nid' => $nid->nid));

I am getting 2 errors:

  • Notice: Trying to get property of non-object in eval() ...
  • Recoverable fatal error: Object of class DatabaseStatementBase could not be converted to string in eval() ...

arg() returns a string so $nid is not an object. You're currently adding your :node_nid database condition with a value of $nid->nid, when you should just be using $nid:

$vid = 1;  
$nid = arg(1);

// Updated as per comments below
$sql = 'SELECT t.name FROM {taxonomy_term_data} t INNER JOIN {taxonomy_index} r ON r.tid = t.tid WHERE t.vid = :vid AND r.nid = :node_nid ORDER BY weight';
$args = array(':vid' => $vid, ':node_nid' => $nid);

$terms = db_query($sql, $args)->fetchCol();
$comma_separated = implode(', ', $terms);

If you want to load the node object related to the current path then you can use menu_get_object(); then you can access the nid as part of the object:

$node = menu_get_object();
$nid = $node->nid;

But I suspect that will be overkill as you only really need the $nid, and not the full node object for your query.

  • Thanks for your quick response. Is there any way I could extract the tags without having to write a query? I'd like to return the values as a string separated by comma. Hope am not asking too much :)
    – Albert
    Mar 10 '12 at 16:07
  • There are other ways (using the Field API functions) but you'll end up with more complicated code for no real benefit (unless there is a radical shift in the way the taxonomy module stores its term/node index in the future, which I think is unlikely). What you're doing is perfectly valid and I think the best/easiest way to do this. I'll update the code in the answer to show you the shortest way to do this :)
    – Clive
    Mar 10 '12 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.