How can I have access to the Drupal 7 $database variable?
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 settin开发者_如何学Cgs.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
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.
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.
精彩评论