I am trying to connect to a different database than what is in my database config file.
I've been able to do this with the following in my model:
$wp['hostname'] = "localhost";
$wp['username'] = "root";
$wp['password'] = "";
$wp['database'] = "transfer";
$wp['dbdriver'] = "mysql";
$wp['dbprefix'] = "";
$wp['pconnect'] = FALSE;
$wp['db_debug'] = TRUE;
$wp['cache_on'] = FALSE;
$wp['cachedir'] = "";
$wp['char_set'] = "utf8";
$wp['dbcollat'] = "utf8_general_ci";
$wpDB = $this->load->database($wp, TRUE);
and then running queries like so: $query = $wpDB->get();
I can only get it to work when the config values are in the model itself (so there would be a lot of duplication). I've tried putting the config array in the constructor, but I get an error that it can't find it.
Where can I put the config array so I don't have to duplicate it and that's available throughout the model?
Database configuration usually goes in config/database.php. You can configure multiple database connections and store them with different group names:
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'host1';
$db['default']['username'] = 'user1';
$db['default']['password'] = '******';
$db['default']['database'] = 'my_db';
$db['other']['hostname'] = 'host2';
$db['other']['username'] = 'user2';
$db['other']['password'] = '******';
$db['other']['database'] = 'my_other_db;
The $active_group refers to the default group when the database class is loaded. To connect to another group in your model, you can use this in the model's __construct method:
$this->db = $this->load->database('other', TRUE);
While this doesn't play nicely with the more flexible $this->load->model('model_name', 'alias', $config) approach, it might be easier.
More info: http://codeigniter.com/user_guide/database/connecting.html
i think that this can help you, directly from codeigniter forum :)
There is a config directory in Code Igniter where you can add your own config file:
system/application/config
In that same directory there is an autoload.php file where you can specify which additional config files you want to load.
You can use the config file from the CodeIgniter.
To retrieve a config var, use:
$this->config->item('item name');
More info in the docs
Since your config data appears to be database related, store them in
system/application/config/database.php
Related
I'm creating a web installer for my app. In the installer, I'll allow the user to enter values for server, username, password and database name.
Now using this values, how would I verify if my app can establish connection with the database
Note: I'm not making use of the config/database.php file. Instead, I'll make use of the posted data by the user and test the connection. If successful, will write those values to the config/database.php
My controller code is as follows:
$host = $this->input->post('dbserver');
$username = $this->input->post('dbusername');
$password = $this->input->post('dbpassword');
$name = $this->input->post('dbname');
if(<can connect with the database using the above>) // <---- This is what I'm looking for
{
// write to the config/database.php file
}
According to the codeigniter documentation you can use manual connecting to your database doing the following :
$config['hostname'] = $this->input->post('dbserver');
$config['username'] = $this->input->post('dbusername');
$config['password'] = $this->input->post('dbpassword');
$config['database'] = $this->input->post('dbname');
$config['dbdriver'] = {driver_to_use};
$config['dbprefix'] = {prefix};
$config['pconnect'] = {bool};
$config['db_debug'] = {bool};
$config['cache_on'] = {bool};
$config['cachedir'] = {cachedir};
$config['char_set'] = {char_set};
$config['dbcollat'] = {dbcollat};
if($this->load->database($config, TRUE))
{
// Write the db config file
}
Following the loader class reference :
Returns : Loaded CI_DB instance or FALSE on failure if $return is set to TRUE, otherwise CI_Loader instance (method chaining)
Ok. I figured it out.
Using TRUE or FALSE as the second parameter to $this->load->database() was always returning an object and hence checking if($this->load->database()) was futile as it would always evaluate to TRUE even with wrong credentials.
So I went ahead and did this:
#$this->load->database($config, FALSE, TRUE); // using # to avoid warnings in case of wrong credentials
if(#$this->db->initialize()) // again use # to avoid error messages
{
// now this verifies it truly connected
}
The ff is my database setup on my config file
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '#########';
$db['default']['database'] = 'fault_analytics';
$db['default']['dbdriver'] = 'mysql';
...
$db['SiteDB']['hostname'] = 'localhost';
$db['SiteDB']['username'] = 'root';
$db['SiteDB']['password'] = '#########';
$db['SiteDB']['database'] = 'smartSiteDB';
$db['SiteDB']['dbdriver'] = 'mysql';
...
my custom jcm_acl.php construct method:
function __construct() {
$this->ci =& get_instance();
$this->ci->load->helper('url');
$this->ci->load->library('session');
$this->ci->load->helper('string');
$this->ci->load->config('jcm_acl');
$this->ci->load->model('jcm_acl_model', 'acl');
$this->tables = $this->ci->config->item('tables');
$this->default_error_page = $this->ci->config->item('default_error_page');
$this->use_default_error_page = $this->ci->config->item('use_default_error_page');
}
I ran some debug queries to check the database captured by my get_instance() on my custom library's __construct() method. The ff are my debug queries:
vdebug($this->jcm_acl->ci->db->database);
vdebug($this->jcm_acl->ci->db->list_tables());
vdebug($this->jcm_acl->ci->db->get('users'));
die();
Below are the results of the debug queries:
Notice the database name being referred to by the get() method, its not the same with the database name as shown by the first debug query. How is this happening.
This only happens when I access the page where I also load the second database. On other pages where I do not load the second database, It works perfectly fine.
I have two files, one config.php and source.php in a subdirectory. In the config file I have something that looks like this
<?php
//app settings
$GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; //ex:
//demo mode
$GLOBALS['demo_mode'] = 0; //possible values: 0 or 1
$GLOBALS['db_table']['sms'] = 'sms_numbers';
$GLOBALS['db_table']['sms_history'] = 'sms_history';
?>
In the config.php file, I have this string $GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; for the base URL and I'd like to make it so that the base URL is automatically detected. I'd like to use something similar to this <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>. I'm using these files under different directories and that's why I'd like to combine them in order to make it automatic without me having to update the base URL manually every time I create a new subdirectory.
Also, inside config.php I have:
//Admin access
$GLOBALS['admin_username'] = 'admin';
$GLOBALS['admin_password'] = 'password';
These values are not in a database but a local file named source.php and I'd like to be able to update the values "admin" and "password" from this source.php file.
Inside the source.php file I guess I'd have to have something thta'd look like this: $username = 'admin';
I'm really sorry but I'm new and would like to learn this stuff. I appreciate any help I can get.
Thank you
Use global constants in config.php
define('APP_URL', 'http://www.website.com/subdirectory');
Then anywhere in the code you can do:
$path = APP_URL . "/path/to/file"
I dont recommend storing admin_username and admin_password as global variables or constants, instead you can create a class in your config.php that contains the values.
Config Example:
config.php
define('APP_URL','http://www.website.com/subdirectory');
define('DEMO_MODE',0); //possible values: 0 or 1
.....
class DB{
var $conn;
public function __construct()
{
$user = "admin";
$pass = "pass";
$host = "127.0.0.1";
$database = "database_name";
$this->conn = mysqli_connect($host, $user, $pass, $database);
}
}
Then in your index.php file you do:
require_once("config.php")
$db = new DB;
$conn = $db->conn();
....
I am upgrading my components from Joomla 1.7 to Joomla 3.3 and have to keep the original database. Therefore I need to access the display data from another database as the installation database. I tried a method that I used many times before with Joomla 2.5 but it seems that I cannot get it right this time.
In my model in the getListQuery() method (which overrides the modellist method) I use the following code to access the database from where I want to get my data:
$dbOptions = getDbOptions();
$db = & JDatabase::getInstance($dbOptions);
where the connection details of my old database are contain in $dbOptions.
I continue to use the following code:
$query = $db -> getQuery(true);
$query -> select('*') -> from('table');
return $query;
I do include the following in the beginning:
jimport('joomla.application.component.modellist');
modellist extends JModelLegacy, therefore I do believe that it uses the following:
/libraries/legacy/model/list.php
But it gives me an error that the table newDatabase.table does not exits and therefore the method I am using does not connect to my old database to retrieve the data from oldDatabase.table.
I am unsure about the inclusion of jimport('joomla.application.component.modellist'); though, could be the problem?
Anyone who can help to retrieve the data from my original database?
If old database on same server and active mysql user has access for it you can use such sql query:
$query = $db -> getQuery(true);
$query -> select('*') -> from('old_database.table');
return $query;
If the entire model is just fetching data from the external database you could use JDatabase->setDbo to replace the default database object with your custom one.
public function __construct($config = array())
{
parent::__construct($config);
$options = array();
$options['driver'] = 'mysqli';
$options['host'] = 'localhost';
$options['user'] = 'username';
$options['password'] = 'password';
$options['database'] = 'database';
$options['prefix'] = 'jos_';
$db = JDatabase::getInstance( $options );
parent::setDbo($db);
}
Now you should be able to access the database in getListQuery() just as you would with your default database. E.g.
$db = JFactory::getDbo();
I believe Adam B's code can have some improvement, regarding setting DB.
public function __construct($config = array())
{
$options = array(
'driver' => 'mysqli',
'host' => 'localhost',
'user' => 'username',
'password' => 'password',
'database' => 'database',
'prefix' => 'jos_'
);
//parent construct will handle setting the DB
$config['dbo']=JDatabase::getInstance( $options );
parent::__construct($config);
}
And getting DB: I think JFactory::getDbo(); will give you the wrong DB, you should do:
self:getDbo();
Using Joomla 2.5, this approach worked for me:
$option = array();
$option['driver'] = 'mysql';
$option['host'] = 'localhost';
$option['user'] = 'XXXXXXXX';
$option['password'] = 'XXXXXXXX';
$option['database'] = 'wordpress';
$option['prefix'] = 'jtt_';
$db = JDatabase::getInstance( $option );
$query = "select * from #__categories";
$db->setQuery($query);
I was able to connect to another database just fine.
I have these lines in my application.ini
how can I read user in my contrroler
resources.doctrine.dbal.connections.default.parameters.driver = "pdo_mysql"
resources.doctrine.dbal.connections.default.parameters.dbname = "zc"
resources.doctrine.dbal.connections.default.parameters.host = "localhost"
resources.doctrine.dbal.connections.default.parameters.port = 3306
resources.doctrine.dbal.connections.default.parameters.user = "root"
resources.doctrine.dbal.connections.default.parameters.password = "123456"
I use of this code but it retuens null
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$user = $bootstrap->getOption('user');
var_dump($user);
edit:
how may I read all of connections options ?
I think you should use
$this->getInvokeArgs('bootstrap');
For more info see this chapter in manual.
What about using
$conf = $bootstrap->getOption('resources');
$dbConf = $conf['doctrine']['dbal']['connections']['default']['parameters'];
How about something like:
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
$connectionParams = $config->resources->doctrine->connections;
Or during Bootstrap, create and save this $config object in the Bootstrap or in the Zend_Registry for later retrieval in your controller.
This goes in your controller.
$bootstrap = $this->getInvokeArg('bootstrap');
$appinidata = $bootstrap->getOptions();
$user=$appinidata['resources']['doctrine']['dbal']['connections']['default']['parameters'] ['user'];
This should print "root".
print_r($user);
To get to the Doctrine container resource, just use :
$bootstrap = $this->getInvokeArg('bootstrap');
$doctrine = $bootstrap->getResource('doctrine');
From there you can drill down to the user name of the default connection (you can specify the connection if needed, just pass the name of the connection in the call to getConnection) :
$username = $doctrine->getConnection()->getUsername();
In this case you should use Zend_Config_Ini class
$config = new Zend_Config_Ini('/path/to/config.ini','staging',$options);
second parameter is a section in INI file should be loaded ;
third parameter is the key to allow modify loaded file.
You can put out value user this way:
$config->resources->doctrine->dbal->connections->default->parameters->user;
you can set any variable using set method as following on index.php inside the public folder
Let
$config = 'test';
Zend_Registry::set('config', $config);
once the variable has been set then you can get on any controllers/models by following method
Zend_Registry::get('config');
Hop it Helps!!