A function to get the term parent
In a Drupal query, ? should never be used. Drupal uses placeholders, which are listed in db_query(), and that allow to 


type casting to a integer the value passed for the %d placeholder
escape the string passed as value for the %s placeholder
convert the value to a floating point value for the %f placeholder
convert and escape the value passed for the %b placeholder 


This means that, for example, db_query("SELECT * FROM {table} WHERE value = %f", "12") would convert the string "12" in the floating point value 12.0, and db_query("SELECT * FROM {table} WHERE string = '%s'", "It's an example") will change the string passed as argument to "It\'s an example".

The query is wrong, in a way, as taxonomy_schema() doesn't define pid (nor classid) as fields of the {term_data} table. The following part of the function will never be executed:

if ($row['pid'] &gt; 0) {
  $term = term_parent($row['pid']);
  $row['classid'] = $term['tid'] . '^' . $row['classid'];
  $row['classname'] = $term['name'] . '^' . $row['name'];
}


The {term_hierarchy} table define a parent field, which is the ID of the parent taxonomy term, but the reported code is not making a join between the tables, and it could not find the ID of the parent taxonomy term, which then is not stored in the pid field.