If you want to access the Drupal database from a standalone script.
Firstly, consider if you can put the PHP code in a Drupal module instead.
Secondly, consider bootstrapping Drupal in your PHP script
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', '/var/www/drupal');
// Bootstrap to database level for db api
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
You can then use the Drupal database API to query content from the Drupal database.
Thirdly, if connecting to a different database is required, consider defining the other database in settings.php and switching to a target database using db_set_active
// Settings.php
$databases['default']['default'] = array(
'driver' => 'mysql',
'database' => 'drupal7',
'username' => 'drupal_user',
'password' => 'drupal_password',
'host' => 'localhost',
'prefix' => '',
);
$databases['other_database']['default'] = array(
'driver' => 'mysql',
'database' => 'other_database',
'username' => 'other_database_user',
'password' => 'other_database_password',
'host' => 'localhost',
'prefix' => '',
);
Then you can switch between databases with db_set_active
// Query other database
db_set_active('other_database');
// $query = db_select('my_table'); // e.g
// Return to default database
db_set_active();