It is possible to create connections to multiple databases using the JDatabase::getInstance() method. The following link points to a tutorial that describes how to create a helper file that makes it easy to create multiple JDatabase instances that point to different databases. You can create the database instances in the following manner using the custom helper class.
$db = JFactory::getDBO();
$db2 = MyDataHelper::getDBO2();
$db3 = MyDataHelper::getDBO3();
You can still get the default database object normally using JFactory.
You can add your own array of options to JDatabaseDriver, like so:
First database:
$db = JFactory::getDbo();
Second database:
$option2 = array();
$option2['driver'] = 'mysqli'; // Database driver name
$option2['host'] = 'localhost'; // Database host name
$option2['user'] = 'DB_USER'; // User for database authentication
$option2['password'] = 'DB_PASS'; // Password for database authentication
$option2['database'] = 'DB_NAME'; // Database name
$option2['prefix'] = 'jos_'; // Database prefix (may be empty)
$db2 = JDatabaseDriver::getInstance($option2);
Third database:
$option3 = array();
$option3['driver'] = 'mysqli'; // Database driver name
$option3['host'] = 'localhost'; // Database host name
$option3['user'] = 'DB_USER'; // User for database authentication
$option3['password'] = 'DB_PASS'; // Password for database authentication
$option3['database'] = 'DB_NAME'; // Database name
$option3['prefix'] = 'jos_'; // Database prefix (may be empty)
$db3 = JDatabaseDriver::getInstance($option3);
Related
This question already has answers here:
Codeigniter - multiple database connections
(8 answers)
Closed 4 years ago.
Afternoon all.
I have a strange question.
I need to have two connections to our db in codeigniter instance.
I need to have the standard ci method but i also need to create a pdo class instance for use in new feature setup.
We are unfortunately in the position where we have to run a v1.0 system using the old db connectivity and a new v2.0 system using a pdo db object.
How can I go about creating a global instance of this pdo class so that it only gets instantiated once per process call to codeigniter.
you should add another DB in application/config/database.php and change dbdriver and hostname like
$db['pdodb']['hostname'] = "mysql:host=localhost'";
$db['pdodb']['username'] = "root";
$db['pdodb']['password'] = "";
$db['pdodb']['database'] = "your_db";
$db['pdodb']['dbdriver'] = "pdo";
$db['pdodb']['dbprefix'] = "";
$db['pdodb']['pconnect'] = TRUE;
$db['pdodb']['db_debug'] = FALSE;
$db['pdodb']['cache_on'] = FALSE;
$db['pdodb']['cachedir'] = "";
$db['pdodb']['char_set'] = "utf8";
$db['pdodb']['dbcollat'] = "utf8_general_ci";
$db['pdodb']['swap_pre'] = "";
$db['pdodb']['autoinit'] = TRUE;
$db['pdodb']['stricton'] = FALSE;
and you can load database like this
$pdodb= $this->load->database('pdodb', TRUE);
and finally you can execute query like this
$query = $pdodb->select('col1, col2,col3')->get('your_table');
for more information about multiple database
I'm using more than 1 DBs in my project. I have a doubt that whether I can select all those DBs with same connection variable or should I use a separate connection for each DB?
Example:
$conn = new MongoClient("mongodb://127.0.0.1:27017");
$dbm = $conn->DB1;
$dbm2 = $conn->DB2;
or
$conn2 = new MongoClient("mongodb://127.0.0.1:27017");
$dbm2 = $conn2->DB2;
Which one is the right approach?
I use the following connection code in open function of a session handler file named sessionhandler.php for establishing connection between session handler and MySql database named AB, for example.
<---sessionhandler.php--->
function _open()
{
global $db;
$hostname_AB = "localhost";
$database_AB = "database";
$username_AB = "user";
$password_AB = "pass";
$AB = mysql_pconnect($hostname_AB, $username_AB, $password_AB) or trigger_error(mysql_error(),E_USER_ERROR);
$db = mysql_select_db($database_AB, $AB) or die("Couldn't select database");
if ($db = mysql_pconnect($hostname_AB, $username_AB, $password_AB))
{
return mysql_select_db('sessionhandler', $db);
}
return FALSE;
}
function _close()
{
global $db;
return mysql_close($db);
}
The problem is that, I can't make query to any other table for example my_table1, my_table2, etc. of AB database using the connection code quoted in the first block above. The first code block only establishes connection between the session handler file sessionhandrer.php & database table sessionhandler only.
In order to make query to other tables of the database AB I had to use seperate connection file that contains the following code:
$hostname_AB = "localhost";
$database_AB = "database";
$username_AB = "user";
$password_AB = "pass";
$AB = mysql_pconnect($hostname_AB, $username_AB, $password_AB) or
trigger_error(mysql_error(),E_USER_ERROR);
Example of a query using above connection code that ignores the connection code of sessionhandler.php :
mysql_select_db($database_AB, $AB);
$query_test = "SELECT users.id, users.name FROM users WHERE users.id = >= 1";
$test = mysql_query($query_test, $AB) or die (mysql_error());
$row_test = mysql_fetch_assoc($test);
$totalRows_test = mysql_num_rows($test);
Absence of the above connection file causes typical MySql connection error in case there are any queries there from other tables of AB database.
How shall I combine these two connection files for making queries to all tables of database AB?
Though I haven't had time to merge these two connection queries into one, mathematical logic says that
if ($db = mysql_pconnect($hostname_AB, $username_AB, $password_AB))
{
return mysql_select_db('sessionhandler', $db);
}
the above block of equation confines the database connection to a single table sessionhandler and primarily that's why query to other tables using this connection code is invalid.
$option = array();
$option['driver'] = 'mysql'; // Database driver name
$option['host'] = 'localhost'; // Database host name
$option['user'] = '*****'; // User for database authentication
$option['password'] = '********'; // Password for database authentication
$option['database'] = 'teste_dados'; // Database name
$db = JDatabase::getInstance( $option );
// Create a new query object.
$query = $db->getQuery(true);
/*
// Insert columns.
$columns = array('id_teste','testes','time');
// Insert values.
$values = array(4,'loucura3',date("h:i:s"));
// Prepare the insert query.
$query->insert($db->quoteName('teste1'));
$query->columns($db->quoteName($columns));
$query->values(implode(',', $values));
or
$query="INSERT INTO teste1('id_teste','testes','time') VALUES (4,'loucura3','".date("h:i:s")."')";
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->execute();
Both options gives the following error message:
An error has occurred while processing your request.
You may not be able to visit this page because of:
an out-of-date bookmark/favourite
a mistyped address
a search engine that has an out-of-date listing for this site
you have no access to this page
Go to the Home Page
Home Page
If difficulties persist, please contact the System Administrator of this site and report the error below.
0 SQL=INSERT INTO teste1('id_teste','testes','time') VALUES (4,'loucura3','05:11:00')
I`ve seen some similar problems and their fixes and none of them workd for me any ideas?.
Try testing the sql script in mysql workbench or phpMyAdmin. Use backticks instead of single quotes around columns
Don't know how to say this, but I have used mysql_insert_id() for many many years. Recently I included it in my web applications and worked well, I have successfully received 50 transactions and was happy.
All of a sudden all my transactions are coming in with ids equal 0, I Google'd around and read something about persistent connection being set to true? I just want me to make sure I give the right info to my network server guy, God knows, whenever something changes, they don't let me know, I only find out when my code all of a sudden breaks.
is there another function to use other than mysql_insert_id() in my PHP/MySQL code?
just for those who want to see code here is what i have: I am not including "id" as it is "auto increment not null primary key, etc"
<?php
$db_host2 = 'localhost';
$db_user2 = 'different';
$db_pass2 = 'different';
$db_name2 = 'different';
$conn2 = &NewADOConnection('mysqlt');
$db2 = $conn2->Connect($db_host2,$db_user2,$db_pass2,$db_name2);
if($conn2->isConnected()==false)
die("Could not connect to the database. Please try again in the next few minutes.");
$db_host = 'localhost';
$db_user = 'admin';
$db_pass = 'pass';
$db_name = 'name';
include_once('adodb/adodb.inc.php');
define('ADODB_FETCH_ASSOC',2);
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$conn = NewADOConnection('mysqlt');
$db = $conn->Connect($db_host,$db_user,$db_pass,$db_name);
if($conn->isConnected()==false)
die("Could not connect to the database. Please try again in the next few minutes.");
$q="insert into tableA(name,address,phone) values ('','','')"
$rs=$conn->execute($q);
$myid=mysql_insert_id();
?>
You just need 1 configuration example :
// database config
$DB_TYPE = "mysql";
$DB_HOST = "xxxxx";
$DB_USER = "xxxx";
$DB_PWD = "xxxx";
$DB_NAME = "xxx";
then use last insert ID for :
$db->Insert_ID