【问题标题】:best way use db_select in Drupal 7 Tpl file?在 Drupal 7 Tpl 文件中使用 db_select 的最佳方法是什么?
【发布时间】:2019-10-20 11:01:36
【问题描述】:

谁能建议我如何在 .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】:

在你的主题 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多