在Drupal 7 Tpl文件中最好的方式使用db_select?

问题描述 投票:-1回答:1

有人可以建议我如何在.tpl文件中编写SQL查询吗?

我试图写db_select('node','n');但这不是最好的方法!我试图在template.php中写这个,但是不行!

我的代码在tpl中运行良好!

请给我一个在tpl文件中编写sql查询的解决方案

我的查询:

    $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;
drupal-7 drupal-modules drupal-theming
1个回答
0
投票

在您的主题template.php文件中,使用预处理功能,例如,用于从mysql获取一些数据并将其传递给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;
  }
}

然后进入您的节点--your_content_type_name.tpl.php打印$ your_variable_name;

© www.soinside.com 2019 - 2024. All rights reserved.