Jommla connect to another database using Multisites extension - php

I'm using Joomla 2.5 and Multisites extensions. When I'm on page X Joomla is using X-database, on page Y using Y-database - it's ok. Unfortunately I have to switch to another database. How I said $db = JFactory::getDbo(); connect to current site database, because Multisites extension works that every page has his own configuration file with database parameters. Any ideas?

Here is solution:
$option['driver'] = 'mysqli';
$option['host'] = 'localhost';
$option['user'] = 'root';
$option['password'] = '';
$option['database'] = 'joomla';
$option['prefix'] = 'a45gy_';
JFactory::destroy();
$db = JDatabase::getInstance($option);
if (JError::isError($db)) {
jexit('Database Error: ' . $db->toString());
}
if ($db->getErrorNum() > 0) {
JError::raiseError(500, 'JDatabase::getInstance: Could not connect to database <br />');
}
parent::setDbo($db);

try it.
$dbX = JDatabase::getInstance(array ('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'prefix'=>null));
$dbY = JDatabase::getInstance(array ('host' => $host, 'user' => $user, 'password' => $pass, 'database' => $database, 'prefix'=>null));

Related

Connecting to AWS RDS via PDO

I have been trying to connect my PHP application to a MySQL database on AWS RDS via PDO. I have seen a similar question here: Unable to connect to AWS RDS through PDO but this is over 4 years old with no definitive answers.
I have tried this a couple of ways. Firstly, passing the host name as '<my-db-name.eu-west-2.rds.amazonaws.com:3306' and secondly passing the port explicitly in the dsn string via
$dsn = $dsn = "mysql:host=" . $this->host . ";port=". $this->port . ";dbname=" . $this->name . ";charset=utf8";
(commented out below). Neither works!
The code snippet is:
$dsn = null;
$options = null;
$this->host = SYSTEM_CONFIG["database"]["host"];
$this->type = SYSTEM_CONFIG["database"]["type"];
$this->name = SYSTEM_CONFIG["database"]["name"];
$this->user = SYSTEM_CONFIG["database"]["user"];
$this->pass = SYSTEM_CONFIG["database"]["pass"];
/* New */
$this->port = SYSTEM_CONFIG["database"]["port"];
switch ($this->type) {
case "SQLSRV":
$dsn = "sqlsrv:Server=" . $this->host . ";Database=" . $this->name;
$options = [
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE => true,
PDO::ATTR_STRINGIFY_FETCHES => false
];
break;
default:
$dsn = "mysql:host=" . $this->host . ";dbname=" . $this->name;
//$dsn = "mysql:host=" . $this->host . ";port=". $this->port . ";dbname=" . $this->name . ";charset=utf8";
$options = [
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_STRINGIFY_FETCHES => false
];
}
try {
$this->pdo = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->logError($e);
} catch (Exception $e) {
$this->logError($e);
}
One thing that does work is to pass the IP address and port as the host name in the form
$this->host = "<IP-address>:3306"
However, I only found the IP address by pinging the host name and I am not sure if this is static or a dynamic IP address (the latter would be no good in a config file!).
Any help on this would be much appreciated!
Have got the code working now, although quite frustratingly I never got to the bottom of why it wasn't working in the first place! I suspect it was something to do with not picking up on the port number properly - maybe a typo somewhere that got 'accidently' corrected (rather than deliberately) when I was trying things out. This code now works (just for MySQL):
$dsn = null;
$options = null;
$this->host = SYSTEM_CONFIG["database"]["host"];
$this->type = SYSTEM_CONFIG["database"]["type"];
$this->name = SYSTEM_CONFIG["database"]["name"];
$this->user = SYSTEM_CONFIG["database"]["user"];
$this->pass = SYSTEM_CONFIG["database"]["pass"];
$this->port = SYSTEM_CONFIG["database"]["port"];
switch ($this->type) {
case "SQLSRV":
// Other untested code...
break;
default:
$dsn = "mysql:host={$this->host};port={$this->port};dbname={$this->name};charset=utf8";
$options = [
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_STRINGIFY_FETCHES => false
];
}
try {
$this->pdo = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->logError($e);
} catch (Exception $e) {
$this->logError($e);
}

PHP connection string to remote database ORA-12154

I have 2 computers:
PC 1 - Here is where I installed the XAMPP.
PC 2 - Here is where my database which is Oracle 9i is installed.
I am using PHP 7 and already added PDO_OCI extension.
Here is my connection string:
define("DB_HOST", "192.168.10.30:1521");
define("DB_NAME", "BACKEND");
define("DB_USER", "sa");
define("DB_PASS", "sa_backend");
new PDO('oci:dbname='. DB_NAME . ';host='. DB_HOST .';', DB_USER, DB_PASS);
When I used this code I am getting this error:
Warning: Uncaught PDOException: SQLSTATE[42S02]: pdo_oci_handle_factory: ORA-12154: TNS:could not resolve the connect identifier specified (ext\pdo_oci\oci_driver.c:709)
UPDATE 1
$server = "192.168.10.30";
$db_username = "sa";
$db_password = "sa_backend";
$service_name = "backend";
$sid = "backend";
$port = 1521;
$dbtns = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = $server)(PORT = $port)) (CONNECT_DATA = (SERVICE_NAME = $service_name) (SERVER = SHARED) (SID = $sid)))";
$this->dbh = new PDO("oci:dbname=" . $dbtns . ";charset=utf8", $db_username, $db_password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
I used this code I found on other stackoverflow link. Now I am getting this error
SQLSTATE[HY000]: pdo_oci_handle_factory: ORA-12520: TNS:listener could not find available handler for requested type of server (ext\pdo_oci\oci_driver.c:728)
I tried to updated the process to 200 even to 400 but the error is still the same.

Connecting To Mongo Replica Set With Doctrine MongoODM Module

We are in the process of updating our API's MongoDB hosting provider from mLab to MongoDB Atlas.
I have updated our connection server to PHP 7.4 with MongoDB PHP extension 1.7.4.
I have updated our API framework from Apigility to Laminas API Tools using the DoctrineMongoODMModule
I can successfully connect using the mongo shell using the following syntax:
mongo "mongodb+srv://test-server-dbteb.mongodb.net/<dbname>" --username <username>
I have looked far and wide to find a sample configuration of the DoctrineMongoODMModule with it's configuration file to connect to a MongoDB Atlas replica set using the mongo+srv:// protocol with no success to this point. Currently the errors are Failed to parse MongoDB URI.
If anyone has had a similar experience, any help would be greatly appreciated.
I had the same issue and im still looking forward to get a real solution.
I directly edited the ConnectionFactory.php in the doctrine-mongo-odm-module (src/DoctrineMongoODMModule/Service/ConnectionFactory.php) with the following code
//...
if (empty($connectionString)) {
$connectionString = 'mongodb+srv://'; //prev: 'mongodb://'
$user = $options->getUser();
$password = $options->getPassword();
$dbName = $options->getDbName();
if ($user && $password) {
$connectionString .= $user . ':' . $password . '#';
}
$connectionString .= $options->getServer() /*. ':' . $options->getPort()*/;
if ($dbName) {
$connectionString .= '/' . $dbName;
}
} else {
// parse dbName from the connectionString
$dbStart = strpos($connectionString, '/', 11);
if ($dbStart !== false) {
$dbEnd = strpos($connectionString, '?');
$dbName = substr(
$connectionString,
$dbStart + 1,
$dbEnd ? ($dbEnd - $dbStart - 1) : PHP_INT_MAX
);
}
}
//...
and in my connection file:
//...
'odm_default' => array(
'server' => '<host>',
'port' => '',
'connectionString' => null,
'user' => '<user>',
'password' => '<psw>',
'dbname' => '<db>',
'options' => array()
),
//...
I think this is the worst possible solution (editing vendor' files) but in my case worked, take that as a temporary fix

PHP CodeIgniter one database per user

I'm trying to use CodeIgniter and DBForge to create a multi tenant app. I'll have my central database with a 'users' table that will store the name of the user and the name of their database.
The problem I'm having is creating the individual databases and their tables. Here's a snippet of the code:
if ($this->dbforge->create_database( $db_name ))
{
echo 'Database created!';
// an array of fields
$fields = array(
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
);
// set them up for the new table
$this->dbforge->add_field($fields);
// create the new table in the new db
$this->dbforge->create_table('items');
}
The database $db_name is created without any problems but when I create the table 'items', it's created on my central database which is not what I want.
Hi when you are trying to create table it is creating table in your default connected database, you have to reconnect your database with user created database and pass that connected database object to $this->db and reforage again than it will create table in user database here how you can create table in user database
if ($this->dbforge->create_database($db_name)) {
echo 'Database created!';
// an array of fields
$config['hostname'] = "localhost";
$config['username'] = "root";
$config['password'] = "";
$config['database'] = $db_name;
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->db = $this->load->database($config, TRUE); //<- magic start from here
$this->load->dbforge();
$fields = array(
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
);
// set them up for the new table
$this->dbforge->add_field($fields);
// create the new table in the new db
$this->dbforge->create_table('items');
}
to make your code more clean create one user_db.php file in application/config and put user config there and every time $config['database'] in your code

authentication in zend

I am using zend auth for authentication. and everything works fine on my local machine.
But when i try to connect to remote server for database than problem starts.
It is not able to login. Is is some problem with session or what..?
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => 'localhost',
'username' => 'root',
'password' => '123456',
'dbname' => 'saet'
));
$form = new Default_Form_Login();
if ($this->getRequest()->isPost()) {
//$db = Zend_Registry::get('db');
$adapter = new Zend_Auth_Adapter_DbTable($db);
$adapter->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setCredentialTreatment('MD5(?)');
$credentialsArray = $this->_request->getParams();
$adapter->setIdentity($credentialsArray['username'])
->setCredential($credentialsArray['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$userInfo = $adapter->getResultRowObject(null, 'password');
// the default storage is a session with namespace Zend_Auth
$authStorage = $auth->getStorage();
$authStorage->write($userInfo);
$this->_helper->FlashMessenger('Successful Login');
return $this->_helper->redirector('index');
} else {
$this->_helper->FlashMessenger->addMessage(array('error',"Invalid Username/Password"));
return $this->_helper->redirector('login');
}
now when i change the db details to remote server. it fails to log in. i m new in zend. and i get application error.
To display errors change your application.ini file as follows
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
and then give us the error.

Categories