I have an associative array contain multiple database configuration and I want to make all connection to database in this array
$dbconfig = array(
'servername' => array('localhost','localhost'),
'username' => array('root1','root2'),
'password' => array('p1','p2'),
'db' => array('db1','db2'),
);
$conn = mysqli_connect($dbconfig['servername'], $dbconfig['username'], $dbconfig['password'], $dbconfig['db']);
You should transpose your array structure to this:
<?php
$dbconfig = array(
array(
'servername' => 'localhost',
'username' => 'root1',
'password' => 'p1',
'db' => 'db1'
),
array(
'servername' => 'localhost',
'username' => 'root2',
'password' => 'p2',
'db' => 'db2'
)
);
Because this allows you to more easily iterate through the array:
for($i = 0; $i < sizeof($dbconfig); $i++) {
$conn[$i] = mysqli_connect($dbconfig[$i]['servername'], $dbconfig[$i]['username'], $dbconfig[$i]['password'], $dbconfig[$i]['db']);
}
Related
I am using phpdocx to generate an array with my data in a docx format.
$contact is an array of multiple object. Sometimes $contact contain 1 object, and sometimes more.
I want to make a loop, to add contact as much as I need.
My problem : For exemple, If I am doing this I will get an error like "Undefined array key 3" if my contact data only contain 3 object or less.
important : Here, if my datas contain 4 object (from 0 to 3 ) it will work but doesn't work when i have 2 objects.
$contact= array(
array(
'name' => $request->get('contact')[0]['name'],
'userName' => $request->get('contact')[0]['userName'],
'number' => $request->get('contact')[0]['number'],
'mail' => $request->get('contact')[0]['mail'],
),
array(
'name' => $request->get('contact')[1]['name'],
'userName' => $request->get('contact')[1]['userName'],
'number' => $request->get('contact')[1]['number'],
'mail' => $request->get('contact')[1]['mail'],
),
array(
'name' => $request->get('contact')[2]['name'],
'userName' => $request->get('contact')[2]['userName'],
'number' => $request->get('contact')[2]['number'],
'mail' => $request->get('contact')[2]['mail'],
),
array(
'name' => $request->get('contact')[3]['name'],
'userName' => $request->get('contact')[3]['userName'],
'number' => $request->get('contact')[3]['number'],
'mail' => $request->get('contact')[3]['mail'],
),
);
$docx->replaceTableVariable($contact, array('parseLineBreaks' => true));
what i am actually trying with no success for the moment : https://www.phpdocx.com/en/forum/default/topic/1773
I have make a loop and it is now working
$contactData = $request->get('contact');
$contactTab = array();
for ($i = 0; $i < count($contactData); $i++) {
$rowData = array(
'name' => $contactData[$i]['name'],
'userName' => $contactData[$i]['userName'],
'number' => $contactData[$i]['number'],
'mail' => $contactData[$i]['mail'],
);
$contactTab[] = $rowData;
}
$docx->replaceTableVariable($contactTab, array('parseLineBreaks' => true));
I tried to take out my database connection from the LocalConfiguration. But it doesn't work on this way. Do you have any ideas how i can realize it. Here what i tried to make it work:
LocalConfiguration.php:
<?php
include_once 'databaseConn.php';
return [
'BE' => [
'debug' => false,
'explicitADmode' => 'explicitAllow',
'installToolPassword' => '$P$CcKE/MYkjKWDzNWsnVZhMBDAttVVrf.',
'loginSecurityLevel' => 'rsa',
],
and in the databaseConn.php:
<?php
$TYPO3_CONF_VARS['DB']['database'] = 'db_name';
$TYPO3_CONF_VARS['DB']['host'] = 'localhost';
$TYPO3_CONF_VARS['DB']['password'] = 'password';
$TYPO3_CONF_VARS['DB']['socket'] = '';
$TYPO3_CONF_VARS['DB']['username'] = 'usr_name';
Hope you can help me.
thanks
Chris
Create a file called AdditionalConfiguration.php in same directory. You can override every value there by addressing it directly
$GLOBALS['TYPO3_CONF_VARS']['DB']['database'] = 'custom';
You can also check the ApplicationContext by $context = GeneralUtility::getApplicationContext()->__toString(); which can be set in a .htaccess or vhost config
Use the following code in AdditionalConfiguration.php:
$configurationSettings = array();
#include_once(__DIR__.'/DatabaseCredentials.php');
#include_once(… some other files …);
if (is_array($configurationSettings)) {
foreach ($configurationSettings as $path => $value) {
$GLOBALS['TYPO3_CONF_VARS'] = \TYPO3\CMS\Core\Utility\ArrayUtility::setValueByPath($GLOBALS['TYPO3_CONF_VARS'], $path, $value);
}
}
unset($configurationSettings);
then set your database credentials in DatabaseCredentials.php:
$configurationSettings = array_merge($configurationSettings, array(
'DB/database' => 'local_database',
'DB/username' => 'local_username',
'DB/password' => 'secret'
));
and you're done.
It is better that you add your database connection code into "LocalConfiguration.php".
return array(
'BE' => array(
'debug' => false,
'explicitADmode' => 'explicitAllow',
'installToolPassword' => '$P$CcKE/MYkjKWDzNWsnVZhMBDAttVVrf.',
'loginSecurityLevel' => 'rsa',
),
'DB' => array(
'database' => 'db_name',
'extTablesDefinitionScript' => 'extTables.php',
'host' => 'localhost',
'password' => 'password',
'socket' => '',
'username' => 'username',
),
I'm trying to create a ZF2 application with multiple databases. Based on a user, the database should be dynamically set.
Right now I've the following:
database.local.php
return array(
'db' => array(
'adapters' => array (
'master_db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=master_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD'
),
'tentant_db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=tenant_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD'
),
)
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Db\Adapter\AdapterAbstractServiceFactory',
)
),
);
For test purposes I've created a form that has a method to fetch some data and put it in a select box. The code to get the database connection is shown in the code below.
MyController.php (in some module)
//... some code
public function someAction(){
$dbAdapter = $this->getServiceLocator()->get('tentant_db');
$form = new AddEolConnectorForm($dbAdapter);
$viewModel = new ViewModel(array(
'form' => $form
));
return $viewModel;
}
//... some more code
My question is, how can I dynamically set the dbname for the tentant_db adapter in my controller (or module)?
Thanks for your help.
The config merge event is one of zend newer event's I believe. It triggers when zend is mergin the config array's which is perfect for the problem you are facing since you can override some array key's dynamically.
public function onMergeConfig(ModuleEvent $e)
{
$configListener = $e->getConfigListener();
$config = $configListener->getMergedConfig(false);
// I'm actually not sure if you have the route match here otherwise you may have to
// use some other method to retrieve the url.
$match = $e->getRouteMatch();
switch ($match) {
case 'first-dependency':
$config['db']['adapter'] => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=master_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD',
),
break;
case 'second-dependency':
$config['db']['adapter'] => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=tenant_db;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD',
),
break;
// Pass the changed configuration back to the listener:
$configListener->setMergedConfig($config);
}
Based on the above answer I've created to following:
Module.php
class Module implements AutoloaderProviderInterface
{
public function init(ModuleManager $moduleManager)
{
$events = $moduleManager->getEventManager();
// Registering a listener at default priority, 1, which will trigger
// after the ConfigListener merges config.
$events->attach(ModuleEvent::EVENT_MERGE_CONFIG, array($this, 'onMergeConfig'));
}
public function onMergeConfig(ModuleEvent $e)
{
$db = $this->getTentantDb();
$configListener = $e->getConfigListener();
$config = $configListener->getMergedConfig(false);
$config['db']['adapters']['tenant_db']['dsn'] = 'mysql:dbname='. $db .';host=localhost';
$configListener->setMergedConfig($config);
}
// Some more code
public function getTenantDb(){
$tenant_db = 'tenant_12345'
return $tenant_db;
}
}
I don't know if it is the best solution, but the above code is working. I think the next steps should be to put the code in a generic module or something so I can access it from all my modules.
How to get all active connection when we use multiple databases?
I have tried:
foreach(Yii::app()->getComponents() as $component)
{
if ($component instanceof CDbConnection)
{
die(var_dump($component));
}
}
but it's look like database component not in Yii::app()->getComponents() result.
My db config:
'db'=>array(
'connectionString' => 'pgsql:host=127.0.0.1;port=yyyy;dbname=db1',
'emulatePrepare' => false,
'username' => 'user1',
'password' => 'pass1',
'schemaCachingDuration' => YII_DEBUG ? 0 : 86400000, // 1000 days
'enableParamLogging' => YII_DEBUG,
'charset' => 'utf8'
),
'db2'=>array(
'class' => 'CDbConnection',
'connectionString' => 'pgsql:host=xxx.xxx.xxx;port=xxxx;dbname=db2',
'emulatePrepare' => false,
'username' => 'user2',
'password' => 'pass2',
'schemaCachingDuration' => YII_DEBUG ? 0 : 86400000, // 1000 days
'enableParamLogging' => YII_DEBUG,
'charset' => 'utf8'
),
If you are in CActiveRecord instance ($model), you can use $model->getDbConnection(); or CActiveRecord::$db to get current connection database;
In class reference you can read:
public array getComponents(boolean $loadedOnly=true)
So, if you want to get every connection instead of only the actives:
foreach (Yii::app()->getComponents(false) as $component)
{
if (is_array($component) && $component['class'] == 'CDbConnection')
{
print_r($component);
}
}
Should list all
I have an array to store the configuration like this
$config = array (
'db' => array(
'db1' => array(
'dbname' => 'mydatabase',
'user' => 'myusername',
'pass' => 'mypassword',
'host' => 'myhost'
)
),
'url' => array(
'homeUrl' => 'http://www.example.com'
)
)
And I'm writing a function to retrieve the data from the array by passing in a string like db.db1.dbname and it supposes to give me 'mydatabase'
I tried to explode the string into an array in order to get the keys, db, db1, and dbname. but after that, I got kinda stuck on how exactly I'm supposed to use them like $config -> db -> db1 -> dbname or $config['db']['db1']['dbname'] in order to get 'mydatabase'.
Ideally, say I have the function named read($arg, $array), and I would like to retrieve results like this
read('db.db1.dbname', $config), returns 'mydatabase'
read('url.homeUrl', $config), returns 'http://www.example.com'
Since I don't know how many keys are contained in the string, I need this to be more dynamic.
Thanks in advance
I think you're thinking about JSON
try $config['db']['db1']['dbname'];
I'm really wondering why you would want to do this, but here it goes:
function read($item, $config)
{
$selectors = explode('.', $item);
$configItem = $config;
foreach($selectors as $selector) {
$configItem = $configItem[$selector];
}
return $configItem;
}
$config = array (
'db' => array(
'db1' => array(
'dbname' => 'mydatabase',
'user' => 'myusername',
'pass' => 'mypassword',
'host' => 'myhost',
),
),
'url' => array(
'homeUrl' => 'http://www.example.com',
),
);
read('db.db1.dbname', $config); // will return mydatabase
Note that you would have to check whether the keys exists and throw an error or exception if that's not the case.
Instead of using the function is there a reason why you cannot do:
function functionThatNeedsDatabaseInfo($databaseInfo)
{
// do database stuff
}
functionThatNeedsDatabaseInfo($config['db']['db1']);
They are just plain nested arrays.
$config['db'] will give you the first inner array
$config['db']['db1'] will give you the array with all the database configurations you're looking for.
$config['db']['db1']['dbname']: 'dbname' is the index in the 'db1' array that will give you the value you want.
function read($layers, $arr){
$toReturn = $arr;
foreach(split('.', $layers) as $layer)
$toReturn = $toReturn[$layer];
return $toReturn;
}
Why would you want to do this, I haven't the foggiest. But there you go.
Cast that thing to an Object! Or rather, cast every array as an object, then you can use it like one.
$config = (object) array (
(object) 'db' => array(
(object) 'db1' => array(
'dbname' => 'mydatabase',
'user' => 'myusername',
'pass' => 'mypassword',
'host' => 'myhost'
)
),
(object) 'url' => array(
'homeUrl' => 'http://www.example.com'
)
)