php - Drupal 8 MySQL数据库查询

标签 php mysql drupal-modules drupal-8

我有一个带有定义路径的自定义模块。我想查询一个单独的数据库(在本地主机内)并通过响应提取此数据,以便它显示在模块的 .twig 页面上。

我正在笔记本电脑上的本地开发环境中工作。只是无法让它发挥作用。我究竟做错了什么?

Controller.php 文件:

namespace Drupal\career_pathways\Controller;
use Symfony\Component\HttpFoundation\Response;

class PathwaysController{
 public function getPaths(){
  $response = new Response();

   $con = \Drupal\Core\Database\Database::getConnection('career_pathways','default');
   $sql = query("SELECT * FROM {pathways}");
   $result = $query->execute();

   if ($result) {
     while ($row = $result->fetchAll()) {
       // Do something with:
       $response = array(
         '#theme' => 'career_pathways',
         '#title' => 'Career Pathways',
         '#markup' => 'A Career Without Boundaries',
         '#firstname' => $row['firstname'],
         '#lastname' => $row['lastname'],
         '#role' => $row['role'],
         '#company' => $row['company']
       );
     }
   }
return $response;
}
}

最佳答案

要在自定义模板文件中显示您的路线,您需要执行以下操作

career_pathways.routing.yml

career_pathways.getpaths:
  path: '/getpaths'
  defaults:
    _controller: '\Drupal\career_pathways\Controller\PathwaysController::getPaths'
    _title: 'getPaths'
  requirements:
    _permission: 'access content'

PathwaysController.php

namespace Drupal\career_pathways\Controller;
use Symfony\Component\HttpFoundation\Response;

use Drupal\Core\Controller\ControllerBase;

class PathwaysController extends ControllerBase {
 public function getPaths(){
   $query = \Drupal::database()->query( "SELECT * FROM pathways" );
   $results = $query->fetchAll();
   $processedResults=[];
    :
   Process your result here
    :

   $build = [
     '#theme' => 'career_pathways',
      '#results' => $processedResults,
    ];
    return $build;
  }
}

career_pathways.module

/**
 * Implements hook_theme().
 */
function career_pathways_theme() {
  return [
    'career_pathways' => [
      'variables' => [
        'results' => NULL,
      ],
      'render element' => 'children',
    ],
  ];
}

templates/career-pathways.html.twig

Hi im working
{{results}}

现在,正确加载模板后。添加您的逻辑并将其传递给 $results 变量

关于php - Drupal 8 MySQL数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793348/

相关文章:

php - 如何从数据库中检查Checkbox Codeigniter?

mysql - Django 从 sqlite 迁移到 MySQL。夹具错误

mysql - 列出一列中不相同的值的 SQL 查询

HTML 表单中的 PHP 搜索代码

php - 使用 PHP PDO 将同一 mysql 列中的值打印到多个列中

php - 无法使用 drupal 模块创建 block

drupal - drupal 8 中上下文链接图标旁边的新设置项

drupal-6 - 如何将自定义表单插入 Drupal 节点 View 并在提交时处理节点数据?

php - 使用 MySQL(和 PHP)搜索可用性?

php - 在 MySql 数据库表中插入日期?