Skip to main content

How to Use Two Database in Yii PHP Framework

Recently in one of Ireland based project client has requirement to use existing Microsoft SQL Server database and implement new feature and store data into MySQL database with Yii Framework.

First we have install and implement microsoft sql server driver in wamp server to make in localhost environment. Now we have to connect both the Database in Yii Framework. Following is steps to implement in Yii Framework :

1. In protected/config folder open main.php and add below code in component for mysql and sql server connection
'db'=>array(  // default mysql connection
 'connectionString' => 'mysql:host=localhost;port=3306;dbname=db_name',
 'emulatePrepare' => true,
 'username' => 'db_username',
 'password' => 'db_password',
 'charset' => 'utf8',
 'tablePrefix' =>'tbl_',  // if have prefix in database tables
),
'msdb'=>array( // microsoft sql server connection
 'class' => 'CDbConnection',
 'connectionString' => 'sqlsrv:Server=host_name or ip_address;Database=db_name',
 'username' => 'db_username',
 'password' => 'db_password',
 'charset' => 'GB2312',
),   

2. Now sql server connection is available in your entire application and access by CDbCommand
$company_name=Yii::app()->msdb->createCommand("SELECT TOP 1 CompanyName from Company_Details WHERE CompanyID="ezeelive")->queryRow();
if(isset($company_name) && !empty($company_name["CompanyName"])):
 echo $company_name["CompanyName"]; // it will print company name Ezeelive Technologies
else:
 echo '';
endif; 

In above example we have use msdb define database connection in component

3. Sometime we require to get the data from one table and insert into another database table, In this case you can use createCommand to write custom loop or you can Switch database connection runtime in model class
class Company extends CActiveRecord
{
 public function init()
 {
 $this->attachEventHandler('OnBeforeSave',   array($this,'switchToWriter'));
 $this->attachEventHandler('OnAfterSave',   array($this,'switchToReader'));
 }
 public function switchToWriter()
 {
 self::$db=Yii::app()->db;
 return true;
 }
 public function switchToReader()
 {
 self::$db=Yii::app()->msdb;
 return true;
 }
 //...
}    

In above example database connection will swapping means the connection will automatically change in fetching and inserting time. "switchToReader" function for fetching the data from SQL Server database and "switchToWriter" for insert/save data into MySQL database.

Please fill free to contact us on info@ezeelive.com or leave a comment for any type of development, integration and coding problem. Keep Coding...!!

Comments

Popular posts from this blog

WhatsApp Chatbot Development in India: A Comprehensive Guide

  WhatsApp has emerged as the most popular messaging platform in India, with over 500 million users . With such a vast user base, businesses are increasingly leveraging WhatsApp chatbots to automate customer interactions, enhance engagement, and drive business growth. This article explores WhatsApp chatbot development in India , its benefits, industries adopting it, the development process, and leading service providers. What is a WhatsApp Chatbot? A WhatsApp chatbot is an AI-powered virtual assistant that interacts with users via WhatsApp Business API . It can handle customer queries, provide support, and automate workflows without human intervention . Why Businesses in India Need WhatsApp Chatbots? 1. Massive User Base WhatsApp is the most widely used messaging app in India, making it the best channel for customer communication. 2. 24/7 Customer Support Automates responses and handles multiple customer queries simultaneously, reducing the need for manual support. 3. Enhanced Cu...

The rise of generative AI startups in India and their impact on businesses

Generative AI startups are reshaping India’s business landscape , driving automation, personalization, and efficiency across industries. With advancements in deep learning, NLP, and computer vision, Indian startups are leveraging Generative AI to create innovative solutions in content creation, healthcare, fintech, e-commerce, and more . 1. The Boom of Generative AI Startups in India Several AI-driven startups in India are developing cutting-edge generative AI models , backed by increasing investments and government support. The rise of Digital India, AI-for-All, and startup incubators has accelerated AI innovation. 2. Key Generative AI Startups in India Ezeelive Technologies Expertise : AI-powered chatbot development and generative AI automation. Impact : Enhances customer engagement, automation, and AI-driven interactions for businesses. Writesonic Expertise : AI-driven content generation for blogs, ads, and copywriting. Impact : Automates content creation for businesses, reducin...

Generative AI Chatbot Services: Revolutionizing Customer Engagement

  Generative AI chatbot services are transforming the way businesses interact with customers. These AI-driven chatbots leverage advanced machine learning models to generate human-like responses, enhancing customer experience, automating repetitive tasks, and driving operational efficiency. With the rise of conversational AI, companies across industries are adopting generative AI Chatbot Services to improve engagement and productivity. What is a Generative AI Chatbot? A generative AI chatbot is an advanced AI-powered virtual assistant that can understand, process, and respond to user queries dynamically. Unlike rule-based chatbots, which rely on predefined responses, generative AI chatbots use machine learning models such as GPT (Generative Pre-trained Transformer) to generate contextually relevant and human-like responses in real-time. Key Features of Generative AI Chatbots Natural Language Processing (NLP): Enhances understanding of human language and improves interactions. Cont...