best way use db_select in Drupal 7 Tpl file?

152 Views Asked by At

Can any one suggest me how to write SQL query in .tpl file?

I tried to write db_select('node', 'n'); But it is not best way! and i tried write this in template.php but not work !

My code work well in tpl!

Please give me a solution to write sql query in tpl file

My Query :

    $node = $variables['node'];
    $author = user_load($node->uid);
    $query = db_select('node', 'n')
    ->condition('n.uid', $author->uid, '=')
    ->condition('type', 'agahi');
    $count_query = $query->countQuery()->execute()->fetchField();
    print $count_query;
1

There are 1 best solutions below

0
khurrami On

in your themes template.php file use preprocess functions for example for getting some data from mysql and passing to node.tpl

function ample_preprocess_node(&$variables) {
  if( $variables['type'] == 'your_content_type_name') {
    $queryresult = db_select('tablename', 'tn')
      ->fields('n')
      ->condition('field_name', 123,'=')
      ->execute()
      ->fetchAll();
  foreach ($queryresult as $queryres) {
    $your_variable_name = $queryres->table_col_name;
  }  
    $variables['your-variable-name'] = $your_variable_name;
  }
}

then in in your node--your_content_type_name.tpl.php print $your_variable_name;