How can I have access to the Drupal 7 $database variable?

旧巷老猫 提交于 2019-12-08 06:32:15

问题


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


回答1:


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.




回答2:


Along with what chx says

Let me count the way you are doing this wrong. You do not write queries into templates. Never. You do not include settings, it's already included. You do not write MySQL queries you use

in your theme's template.php file you have access to most of the variables coming to page.tpl.php. use

hook_preprocess(&$variables, $hook);

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.



来源:https://stackoverflow.com/questions/6146173/how-can-i-have-access-to-the-drupal-7-database-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!