Get data from another Database in Codeigniter MySQL - mysql

I want to get data from another DB in MySQL except the defualt DB. I added the following line into my model in addition to the excisting code. Another DB as 'storesDB'.
$this->load->database('storesDB', TRUE);
My model as follows :
public function getEquipment($id = null)
{
$this->db->select('*');
$this->db->from('tbl_equipment');
$this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
$this->db->where("tbl_equipment.status", '1');
if ($id)
$this->db->where("tbl_equipment.id", $id);
$query = $this->db->get();
return $query->result();
}
The code is working properly. But the code got data from defualt DB not the by the 'storesDB'.
Modified code is as follows :
public function getEquipment($id = null)
{
$this->load->database('storesDB', TRUE);
$this->db->select('*');
$this->db->from('tbl_equipment');
$this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
$this->db->where("tbl_equipment.status", '1');
if ($id)
$this->db->where("tbl_equipment.id", $id);
$query = $this->db->get();
return $query->result();
}
What may be the reason?

The reason is that you don't assign the second database properly. You also need to setup the correct config for the 2nd database
$config['hostname'] = "host";
$config['username'] = "user";
$config['password'] = "pass";
$config['database'] = "storesDB";
// etc..
then you load the database:
$this->db2 = load->database($config, TRUE);
now you have $this->db, the default database and $this->db2, the second database
and continue your code like:
$this->db2->select('*');
$this->db2->from('tbl_equipment');
// etc...

I have no experience in Codeigniter, but in a standar sql query you can add the database name in front of the table to get info from another db like:
SELECT * FROM sakila.actor;
Assuming you are not connected to sakila db.
Using this aproach both databases must have same credentials

Related

How to fetch data from database with 3 parameters Laravel

I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.
$detail = Barang_Keluar_Detail::findOrFail($id); //15
$cariid = $detail->pluck('barang_keluar_id');
$instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
$instansiid = $instansiquery->pluck('instansi_id');
$tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31
and the parameter are here
$cariinstasama = Barang_Keluar::where('id', $cariid)
->orWhere(function ($query) use($instansiid, $tanggal) {
$query->where('tanggal', "'$tanggal'")
->where('instansi_id', $instansiid);
});
Please any help will be appreciated, thank you.
Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:
$cariinstasama = Barang_Keluar::where('id', $cariid)
->when($instansiid, function ($query, $instansiid) {
return $query->where('instansi_id', $instansiid);
})
->when($tanggal, function ($query, $tanggal) {
return $query->where('tanggal', $tanggal);
})->get();
For more info see https://laravel.com/docs/5.8/queries#conditional-clauses
You can try this as well.
$cariinstasama = Barang_Keluar::where('id', $cariid);
if($instansiid !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
if($tanggal !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
$result = $cariinstasama->get();
Its not clear what exactly you want.
Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :
$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
$query = $query->where( // if yes apply more parameters to the query
[
['col1', $param1],
['col2', $param2]
]
);
else
$query = $query->where('col1', $param1);
$results = $query->get();
Hope it helps....

codeigniter 3 $query = $this->db->query($queri_str); return 0 result

Good morning,
I have a problem with mysql and coeigniter 3.
if I request data with
$ query = $ this-> db-> query ($ queri_str);
it does not give me results.
if I enter the query on phpmyadmin it shows me two results.
$ queri_str = 'SELECT * FROM `my_table` WHERE` id_mytable2` = "'. $ id_name. '"';
The database tables were created with mysql workbench and automatically the reference to the main table with a 1: n ratio was added
Try this query
$this->db->select('*');
$this->db->where('id', '58e5j0m5bqrs7hk8suokko28hj7ni0v6');
$result = $this->db->get('ci_sessions')->result_array();
print_r($result);
Try this solution, you want to do a normal select,I don't know the query your wrote but
public fucntion get_data($id){
$this->db->select('*');
$this->db->from('your_table');
$this->db->where('id','=' ,'$id');
$query = $this->db->get();
$data = $query->result_array();
return $data;
}
the problem is back.
I'll explain.
function myfunction($id_myname) {
$this->db->select('*');
$this->db->where('id_myname', $id_myname);
//$query = $this->db->get('my_table');
$query = $this->db->get('my_table');
//print_r($query);
//var_dump($query);
if ( !$query ){
$error = $this->db->error(); // Has keys 'code' and 'message'
}
return $query->result();
}
when I call this function an empty value comes back to me.
While if I enter the value of the query in phpmyadmin I find two values

How to conditionally use different database in CodeIgniter

Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .

Getting data from related table in Codeigniter -- translating MySQL query into CI MVC

I have worked with examples from a few different StackOverflow posts to get data from related tables in CI, but haven't been successful in connecting my tables in the "where" part, and I'd like to understand how to translate that from a MySQL query to the CI MVC.
This is the MySQL query that works to get the dctag fields from the dctags table where the dctag_id in the articles table matches:
$dctagger = $article['dctag_id'];
$query = "SELECT `dctitle`, `dctag_id` FROM dctags WHERE dctag_id = '$dctagger'";
$query_run = mysql_query($query);
This is the code for the Model, Controller, and View files:
Model -
public function get_article_dctag() {
$this->db->select('*')
->from('dctags')
->where('dctag_id', $this->$data['dctag_id']);
$query = $this->db->get();
return $query->result_array(); }
Controller -
public function article($slug) {
$data['article'] = $this->article_model->get_article($slug);
$data['dctag'] = $this->article_model->get_article_dctag();
$this->load->view('templates/header-article', $data);
$this->load->view('article', $data);
$this->load->view('templates/footer-home'); }
View -
<?php foreach ($dctag as $dctag_item): ?>
<title><?php $dctag_item['dctitle']; ?></title>
<?php endforeach; ?>
Error -
"A PHP Error was encountered... Severity: Notice... Message: Undefined variable: data...Filename: models/article_model.php" (see Model code above)
The problem is the variable $this->... and I don't know what that needs to be. Thanks for explanations/clarification -- in advance!
If your dctag_id is in $data['article'] then use following code
On Controller
public function article($slug)
{
$data['article'] = $this->article_model->get_article($slug);
$data['dctag'] = $this->article_model->get_article_dctag($data['article']['dctag_id']);
$this->load->view('templates/header-article', $data);
$this->load->view('article', $data);
$this->load->view('templates/footer-home');
}
On your Model
public function get_article_dctag($id)
{
$this->db->select('*')
->from('dctags')
->where('dctag_id', $id);
$query = $this->db->get();
return $query->result_array();
}
In the controller you should pass the variable on the get_article_dctag($var)
This will be the reference on your model get_article_dctag() and this should have a parameter of what you are searching for. In your structure it seems that Model cant locate your $data['dctag_id'] in your function
In the controller
$dctag_id = 2
$this->article_model->get_article_dctag($dctag_id);
In your model
function get_article_dctag($dctag_id){
$this->db->where('dctag_id',$dctag_id);}
Hopes it will help you a lot

Symfony2 execute SQL file in Doctrine Fixtures Load

I'm migrating an old web app based on SQL Server and ASP to Symfony2 and MySQL. I made some queries and export old data to individual SQL files.
How can I execute thoses files in my fixtures, when I run the command
$php app/console doctrine:fixtures:load
Now I have some fixtures that works directly with Doctrine ORM and entities, but I have a lot of data to import.
I find a good solution. I didn't find an exec method in class ObjectManager, so... this work very well for me.
public function load(ObjectManager $manager)
{
// Bundle to manage file and directories
$finder = new Finder();
$finder->in('web/sql');
$finder->name('categories.sql');
foreach( $finder as $file ){
$content = $file->getContents();
$stmt = $this->container->get('doctrine.orm.entity_manager')->getConnection()->prepare($content);
$stmt->execute();
}
}
In this solution your fixture class has to implement the ContainerAwareInterface with the method
public function setContainer( ContainerInterface $container = null )
{
$this->container = $container;
}
You can load the file contents as a string, and execute native SQL using the EntityManager:
class SQLFixtures extends AbstractFixture implements OrderedFixtureInterface
{
$filename = '/path/to/sql/file.sql';
public function load(ObjectManager $manager) {
$sql = file_get_contents($filename); // Read file contents
$manager->getConnection()->exec($sql); // Execute native SQL
$manager->flush();
}
public function getOrder() {
return 99; // Order in which this fixture will be executed
}
}
Answer for Zend Framework 2.5.3 using Doctrine Data-Fixtures.
Not sure if this applies to the given answers, but they are trying a bit too hard. If you inspect the given $manager object, you'll find that it already is the EntityManager (of interface ObjectManager) (at least, in ZF2). As such you're able to get the Connection directly and it's possible to execute without using $this->container->get('doctrine.orm.entity_manager')
Below a snippet which I use for creating the first user "system", with a createdBy FK reference to itself.
public function load(ObjectManager $manager)
{
$sql = 'INSERT INTO users (
id, username, email, display_name, `password`, created_by)
VALUES (:id, :username, :email, :display_name, :password, :created_by)';
$password = $this->createSuperDuperEncryptedPassword();
// $manager === `EntityManager|ObjectManager`, `->getConnection()` is available
$stmt = $manager->getConnection()->prepare($sql);
$stmt->bindValue(':id', 1);
$stmt->bindValue(':username', 'system');
$stmt->bindValue(':email', 'system#system.test');
$stmt->bindValue(':display_name', 'system');
$stmt->bindValue(':password', password );
$stmt->bindValue(':created_by', 1); // Self reference
$stmt->execute();
}