PHP CodeIgniter one database per user - php

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

Related

Google API Client - Create user with another email

I started using the php quickstart to connect and create users. Everything works, but cannot add a second email address.
The help is confusing, and can't find an example.
My code so far:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// USER DATA
$userName = 'Test';
$userSurname = 'User';
$userDocument = '12345678';
$userEmail = 'test#mail.com';
$name = new Google_Service_Directory_UserName();
$email = new Google_Service_Directory_UserEmail();
$user = new Google_Service_Directory_User();
// CREATE USER TO INSERT
$name->setGivenName($userName);
$name->setFamilyName($userSurname);
$name->setFullName($userName . ' ' . $userSurname);
$email->setAddress($userEmail);
$email->setType('home');
$user->setName($name);
$user->setHashFunction('SHA-1');
$user->setPassword(hash('sha1', $userDocument));
$user->setPrimaryEmail($userName . '.' . $userSurname . '#domain.com');
$user->setSuspended(false);
$user->setChangePasswordAtNextLogin(true);
$user->setEmails(array('address' => 'test#mail.com', 'type' => 'home', 'customType' => '', 'primary' => false)); // don't work
// $user->setEmails($email); // don't work either
$user->setOrgUnitPath('/org/path');
try
{
$createUserResult = $service->users->insert($user);
}
I find the error. The setEmails method receives an multidimensional array, so:
$user->setEmails(array(array('address' => 'test#mail.com', 'type' => 'home', 'customType' => '', 'primary' => false)));

Adding a new invoice line in existing invoice is not working

I am facing a problem while adding a new invoice line in existing invoice from Mysql database.
I have synced the invoice from quickbook to MySql. Two-way sync is working between quickbook and mysql.
The problem is when I add a new invoicline in qb_invoice_invoicline table, It does not sync with Quickbook. Following error I received in qb_invoice table. qbsql_last_errnum 320 last_error_msg
Object "64-1518123234" specified in the request cannot be found. (here 64-1518123234 is the value in qb_invoice_invoiceline.TxnLineID coulmn).If I leave this field blank then there is a parsing error when syncing.
Following is the code I am using to sync.
<?php
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 1);
require_once dirname(__FILE__) . '/QuickBooks.php';
require_once 'Common/Constants.php';
require_once 'Common/Utility.php';
require_once 'Common/Hook.php';
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set(TIMEZONE);
}
if(!isset($_GET['companyId'])) {
trigger_error('Error! Parameter "CompanyId" missing in API.', E_USER_ERROR);
return;
}
$companyId = $_GET['companyId'];
$companyConfig = file_get_contents('config.json');
$companyData = json_decode($companyConfig, true);
if(!isset($companyData['company'][$companyId])) {
trigger_error('Error! Company detail not found in config file.', E_USER_ERROR);
return;
}
// The username and password the Web Connector will use to connect with
$username = $companyData['company'][$companyId]['web_connector_username'];
$password = $companyData['company'][$companyId]['web_connector_password'];
// get Company Database credentials
$db = $companyData['company'][$companyId];
$dsn = 'mysqli://' . $db['username'] . ':' . $db['password'] . '#' . $db['host'] . '/' . $db['db_name'];
// If the database has not been initialized, we need to initialize it (create
// schema and set up the username/password, etc.)
if (!QuickBooks_Utilities::initialized($dsn))
{
header('Content-Type: text/plain');
// It takes a really long time to build the schema...
set_time_limit(0);
$driver_options = array(
);
$init_options = array(
'quickbooks_sql_enabled' => true,
);
QuickBooks_Utilities::initialize($dsn, $driver_options, $init_options);
QuickBooks_Utilities::createUser($dsn, $username, $password);
exit;
}
$mode = QuickBooks_WebConnector_Server_SQL::MODE_READWRITE;
$conflicts = QuickBooks_WebConnector_Server_SQL::CONFLICT_LOG;
$delete = QuickBooks_WebConnector_Server_SQL::DELETE_FLAG; // Just flag it as deleted
$hook_obj = Hook::getInstance($companyId);
$hooks = array(
QuickBooks_SQL::HOOK_SQL_INSERT => array(
'preHookHandler',
array( $hook_obj, 'insertHook' ),
),
QuickBooks_SQL::HOOK_SQL_UPDATE => array(
'preHookHandler',
array( $hook_obj, 'updateHook' ),
),
);
function preHookHandler($requestID, $user, $hook, &$err, $hook_data, $callback_config)
{
return true;
}
$soap_options = array();
$handler_options = array(
'deny_concurrent_logins' => false,
'deny_reallyfast_logins' => false,
);
$driver_options = array();
$ops = array(
QUICKBOOKS_OBJECT_ACCOUNT,
QUICKBOOKS_OBJECT_SALESTAXITEM,
QUICKBOOKS_OBJECT_SALESTAXCODE,
QUICKBOOKS_OBJECT_CUSTOMER,
QUICKBOOKS_OBJECT_VENDOR,
QUICKBOOKS_OBJECT_INVENTORYITEM,
QUICKBOOKS_OBJECT_TEMPLATE,
QUICKBOOKS_OBJECT_CUSTOMERTYPE,
QUICKBOOKS_OBJECT_VENDORTYPE,
QUICKBOOKS_OBJECT_ESTIMATE,
QUICKBOOKS_OBJECT_INVOICE,
QUICKBOOKS_OBJECT_CLASS,
QUICKBOOKS_OBJECT_UNITOFMEASURESET,
QUICKBOOKS_ADD_UNITOFMEASURESET,
QUICKBOOKS_MOD_UNITOFMEASURESET,
QUICKBOOKS_QUERY_UNITOFMEASURESET,
QUICKBOOKS_IMPORT_UNITOFMEASURESET,
QUICKBOOKS_OBJECT_STANDARDTERMS,
QUICKBOOKS_OBJECT_INVENTORYITEM,
QUICKBOOKS_OBJECT_NONINVENTORYITEM,
QUICKBOOKS_OBJECT_SERVICEITEM,
QUICKBOOKS_OBJECT_SHIPMETHOD,
QUICKBOOKS_OBJECT_PAYMENTMETHOD,
QUICKBOOKS_OBJECT_TERMS,
QUICKBOOKS_OBJECT_PRICELEVEL,
QUICKBOOKS_OBJECT_ITEM,
QUICKBOOKS_ADD_SERVICEITEM,
QUICKBOOKS_MOD_SERVICEITEM,
QUICKBOOKS_QUERY_SERVICEITEM,
QUICKBOOKS_IMPORT_SERVICEITEM,
QUICKBOOKS_OBJECT_RECEIVEPAYMENT,
QUICKBOOKS_ADD_RECEIVE_PAYMENT,
QUICKBOOKS_MOD_RECEIVE_PAYMENT,
QUICKBOOKS_QUERY_RECEIVE_PAYMENT,
QUICKBOOKS_IMPORT_RECEIVE_PAYMENT,
QUICKBOOKS_DERIVE_RECEIVE_PAYMENT,
QUICKBOOKS_OBJECT_PAYMENTMETHOD,
QUICKBOOKS_OBJECT_COMPANY,
QUICKBOOKS_OBJECT_HOST,
QUICKBOOKS_OBJECT_PREFERENCES,
QUICKBOOKS_QUERY_DELETEDTRANSACTIONS,
QUICKBOOKS_OBJECT_SALESREP,
QUICKBOOKS_OBJECT_DATAEXT,
QUICKBOOKS_ADD_DATAEXT,
QUICKBOOKS_MOD_DATAEXT,
QUICKBOOKS_OBJECT_DATAEXTDEF,
QUICKBOOKS_ADD_DATAEXTDEF,
QUICKBOOKS_MOD_DATAEXTDEF
);
$ops_misc = array( // For fetching inventory levels, deleted transactions, etc.
QUICKBOOKS_DERIVE_INVENTORYLEVELS,
QUICKBOOKS_QUERY_DELETEDLISTS,
QUICKBOOKS_QUERY_DELETEDTRANSACTIONS
// 'nothing',
);
//
$sql_options = array(
'only_import' => $ops,
'only_add' => $ops,
'only_modify' => $ops,
'only_misc' => $ops_misc,
);
//
$callback_options = array();
$Server = new QuickBooks_WebConnector_Server_SQL(
$dsn,
'1 minute',
$mode,
$conflicts,
$delete,
$username,
array(),
array(),
$hooks,
QUICKBOOKS_LOG_DEVELOP,
QUICKBOOKS_SOAPSERVER_BUILTIN,
QUICKBOOKS_WSDL,
$soap_options,
$handler_options,
$driver_options,
$sql_options,
$callback_options);
$Server->handle(true, true);
To summarize the problem what value should be in (qb_invoice_invoiceline.TxnLineID) column to add a new invoiceline ?
If you are trying to just add a line, set the TxnLineID to -1 for all the new line items.
For example, if your Invoice has line items with IDs A/B/C, and you want to append another line, your mod should be something like:
...
<InvoiceLineMod><TxnLineID>A</TxnLineID><InvoiceLineMod>
<InvoiceLineMod><TxnLineID>B</TxnLineID><InvoiceLineMod>
<InvoiceLineMod><TxnLineID>C</TxnLineID><InvoiceLineMod>
<InvoiceLineMod>
<TxnLineID>-1</TxnLineID>
< ... other required values... >
<InvoiceLineMod>
...
If you wanted to delete line B, just send
<InvoiceLineMod><TxnLineID>A</TxnLineID><InvoiceLineMod>
<InvoiceLineMod><TxnLineID>C</TxnLineID><InvoiceLineMod>

consolibyte : QuickBook two way syncing with MySql database is not working

I am trying to implement two way syncing with quickbook using consolibyte library. I have used consolibyte example file "example_mysql_mirror.php". It creates around 139 tables and import data from Quickbook successfully.
When I made some changes in Quickbook and MySql database, Quickbook changes reflects in MySql database but MySql dabase changes does not appear in Quickbook.
I am using QuickBook enterprise 2018 and consolibyte stable build 2.0.0.
Fallowing are the content of "example_mysql_mirror.php" file.
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
require_once dirname(__FILE__) . '/../QuickBooks.php';
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set('America/New_York');
}
$username = 'Admin';
$password = '123456';
$dsn = 'mysqli://root:#localhost/quickbooks_sql';
if (!QuickBooks_Utilities::initialized($dsn))
{
header('Content-Type: text/plain');
set_time_limit(0);
$driver_options = array(
);
$init_options = array(
'quickbooks_sql_enabled' => true,
);
QuickBooks_Utilities::initialize($dsn, $driver_options, $init_options);
QuickBooks_Utilities::createUser($dsn, $username, $password);
exit;
}
$mode = QuickBooks_WebConnector_Server_SQL::MODE_READWRITE;
$conflicts = QuickBooks_WebConnector_Server_SQL::CONFLICT_LOG;
$delete = QuickBooks_WebConnector_Server_SQL::DELETE_FLAG;
$hooks = array();
$soap_options = array();
$handler_options = array(
'deny_concurrent_logins' => false,
);
$driver_options = array();
$ops = array(
QUICKBOOKS_OBJECT_SALESTAXITEM,
QUICKBOOKS_OBJECT_SALESTAXCODE,
QUICKBOOKS_OBJECT_CUSTOMER,
QUICKBOOKS_OBJECT_VENDOR,
QUICKBOOKS_OBJECT_INVENTORYITEM,
QUICKBOOKS_OBJECT_TEMPLATE,
QUICKBOOKS_OBJECT_CUSTOMERTYPE,
QUICKBOOKS_OBJECT_VENDORTYPE,
QUICKBOOKS_OBJECT_ESTIMATE,
QUICKBOOKS_OBJECT_INVOICE,
QUICKBOOKS_OBJECT_CLASS,
QUICKBOOKS_OBJECT_INVOICE,
QUICKBOOKS_OBJECT_PAYMENTMETHOD,
QUICKBOOKS_OBJECT_COMPANY,
QUICKBOOKS_OBJECT_HOST,
QUICKBOOKS_OBJECT_PREFERENCES,
);
$ops_misc = array(
QUICKBOOKS_DERIVE_INVENTORYLEVELS,
QUICKBOOKS_QUERY_DELETEDLISTS,
QUICKBOOKS_QUERY_DELETEDTRANSACTIONS,
// 'nothing',
);
$sql_options = array(
'only_import' => $ops,
'only_add' => $ops,
'only_modify' => $ops,
'only_misc' => $ops_misc,
);
$callback_options = array();
$Server = new QuickBooks_WebConnector_Server_SQL(
$dsn,
'1 minute',
$mode,
$conflicts,
$delete,
$username,
array(),
array(),
$hooks,
QUICKBOOKS_LOG_DEVELOP,
QUICKBOOKS_SOAPSERVER_BUILTIN,
QUICKBOOKS_WSDL,
$soap_options,
$handler_options,
$driver_options,
$sql_options,
$callback_options);
$Server->handle(true, true);
If your QuickBooks computer in this time zone?
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set('America/New_York');
}
If not, fix your code so that the timezone of this code matches the timezone of QuickBooks.

Jommla connect to another database using Multisites extension

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));

Querying a Clarizen Project/Task in PHP

I'm currently trying to get a list of all Clarizen active projects so that I can modify some properties of its tasks. I've read the Clarizen API but it doesn't have many informations on PHP queries. What I managed to do so far is to query all the projects and then test their status one by one. In practice this is not a good approach since I have thousands of projects and not all of them are listed at once. Here's the code:
//LOGIN PROCCESS
$soapUrl = 'https://api.clarizen.com/v1.0/Clarizen.svc?WSDL';
$soapApiUrl = 'http://clarizen.com/api';
$soapConfig = array('exceptions' => 1);
$request = array();
$params = array(
'userName' => $username,
'password' => $password
);
$client = new SoapClient($soapUrl, $soapConfig);
$response = $client->Login($params);
$sessionId = $response->LoginResult->SessionId;
$userId = $response->LoginResult->UserId;
//Create a SOAP header containing the session ID for future requests
$header = new SoapHeader($soapApiUrl, 'Session', array("ID"=>$sessionId));
$client->__setSoapHeaders($header);
//Create a Query object
$userQuery = new stdClass();
//Set the name of the entity type you are querying
$userQuery->TypeName = 'Project';
//Select the fields you want retrieved from that entity
$userQuery->Fields = array('Name', 'State');
/* Doesnt work...*/
/*
$userQuery->Where = new stdClass();
$userQuery->Where->LeftExpression = new stdClass();
$userQuery->Where->LeftExpression->FieldName = 'State';
$userQuery->Where->Operator = 'Equal';
$userQuery->Where->RightExpression = new stdClass();
$userQuery->Where->RightExpression->Value = new stdClass();
$userQuery->Where->RightExpression->Value->TypeName = 'State';
$userQuery->Where->RightExpression->Value->Value = 'Active';
*/
$request[] = new SoapVar($userQuery, SOAP_ENC_OBJECT, 'EntityQuery', 'http://clarizen.com/api/queries');
//Execute the request
$result = $client->Execute(array("request"=>$request));
3 questions follow:
What is the right way to query in PHP with the "WHERE" clause
How to fetch the tasks of this project and then, for example create a Stopwatch for it.
How to continue the query until the hasMore flag is 0, or is there a way to fetch the entire thing all at once?
Thanks in advance.

Categories