azri
azri

Reputation: 84

get database config settings to controller/views in codeigniter

I am using Codeigniter 3 and I got a page to download a backup .sql file (its working well).The problem is i need to change the config both on config/database.php and db.php if i upload my project into server.So what i want is to only change the config/database.php when upload to the server

config/database.php :

$db['default'] = array(
'dsn'   => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'my_database',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

views/db.php :

$mysqlUserName      = "root";
$mysqlPassword      = "";
$mysqlHostName      = "localhost";
$DbName             = "my_database";
$backup_name        = "mybackup.sql";

Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName,  $tables=false, $backup_name=false );

controller :

  public function backup()
  {
   if ($this->data['user_profile']['user_group'] > 2)
  {
   return show_404('The page you requested was not found.');
  }else {
   $this->load->view('db');

   redirect('admin/setting/backup','refresh');
   }
  }

i just tried with this method but its obviously wrong :

$mysqlUserName      = $db['username'];
$mysqlPassword      = $db['password'];
$mysqlHostName      = $db['hostname'];
$DbName             = $db['database'];

Upvotes: 0

Views: 664

Answers (2)

mail2bapi
mail2bapi

Reputation: 1617

You can get the config values to the controller or view by using $this->config->item($item [, $index='']) method. Learn more in documentation.

Example:

$mysqlUserName      = $this->config->item('username', 'default');
$mysqlPassword      = $this->config->item('password', 'default');
$mysqlHostName      = $this->config->item('hostname', 'default');
$DbName             = $this->config->item('database', 'default');

Upvotes: 1

Godya Aditya
Godya Aditya

Reputation: 179

Here, use this in your controller:

public function index()
{
    $this->load->database();  //load the driver first
    $mysqlUserName      = $this->db->username;
    $mysqlPassword      = $this->db->password;
    $mysqlHostName      = $this->db->hostname;
    $DbName             = $this->db->database;
}

if you have multiple database, you can use $this->load->database('dbname_you_want_to_use')

Upvotes: 1

Related Questions