如何访问 Drupal 7 $database 变量?
我在node.tpl.php和page.tpl.php中编写了一些php/mysql查询。
这些页面用于连接 MySQL 的用户名和密码在文件中指定。
我希望能够使用 Drupal 的 settings.php 文件中定义的 MySQL 连接设置,而不是这样做。
我正在尝试将settings.php 文件包含到node.tpl.php 和page.tpl.php 中,但未成功。
<?php include("sites/default/settings.php") ?>
然后我尝试从 settings.php 访问 $databases 数组,如下所示:
$databases['default']['default']['username']
$databases 数组具有以下结构:
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'sdnndr',
'username' => 'root',
'password' => '',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
我的方法不起作用。任何人都可以建议
I have written some php/mysql queries inside node.tpl.php and page.tpl.php.
The username and password that these pages use to connect to MySQL are specified within the files.
Instead of doing this, I would like to be able to use the MySQL connection settings that are defined in Drupal's settings.php file.
I am trying, unsuccessfully include the settings.php file into node.tpl.php and page.tpl.php.
<?php include("sites/default/settings.php") ?>
Then I am trying to access the $databases array from settings.php like this:
$databases['default']['default']['username']
The $databases array has this structure:
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'sdnndr',
'username' => 'root',
'password' => '',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
My approach is not working. Can anyone suggest
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我数一下你做错的方式。您无需将查询写入模板中。绝不。因为如果你稍后改变外观,你就会失去逻辑。将它们放在它们所属的模块中。您不需要包含设置,它已经包含在内。您不编写 MySQL 查询,因为它们不安全,而是使用 http://api.drupal.org/api/drupal/includes--database--database.inc/group/database/7 它鼓励(在某些情况下甚至强制执行)安全性。
Let me count the way you are doing this wrong. You do not write queries into templates. Never. Because if you change looks later you would lose your logic. Put them in modules where they belong. You do need not include settings, it's already included. You do not write MySQL queries because they are insecure, instead you use http://api.drupal.org/api/drupal/includes--database--database.inc/group/database/7 which encourages (and in some case even enforces) security.
随着 chx 所说
在主题的 template.php 文件中使用的 MySQL 查询,您可以访问 page.tpl.php 中的大多数变量。使用
然后转储或 dsm($variables); (必须安装开发模块)。
如果您确实需要查询数据库,请创建一个小模块,并在 .module 文件中使用 drupal 函数来查询数据库。您也不必担心连接到数据库,这是在引导过程中完成的。
Along with what chx says
in your theme's template.php file you have access to most of the variables coming to page.tpl.php. use
Then dump or dsm($variables); (devel module must be installed).
If you really need to query the database, create a small module and in the .module file use drupal functions to query the database. There also you dont have to worry about connecting to database, that is done in the bootstrap process.