Codeigniter : How to join 2 tables in databases from 2 different connections - codeigniter

I made two database connections in database.php, one for reading which is my localhost machine and one for writing "insert" which is an online database.
But I ran into this problem when I wanted to join the two tables "answers" in the localhost database and "user" in the online database.
function get_users() {
$write_db = $this->load->database('default', TRUE); /* database conection for localhost DB */
$read_db = $this->load->database('read', TRUE); /* database conection for online DB */
$read_db->select('*');
$read_db->from('ibitstore.user');
$write_db->join('english.answers','ibitstore.user.user_id = english.answers.user_id');
$query = $read_db->get();
if($query->num_rows() > 0)
return $query->result_array();
return array();
}
When I use $write_db with the join clause
$write_db->join('english.answers','ibitstore.user.user_id = english.answers.user_id');
data is retrieved from the online database but not from the localhost database, like it ignored the join I tried to use:
$read_db->join('english.answers','ibitstore.user.user_id = english.answers.user_id');
Then I got this SQL error. Looks like it thought that the "answers" table is on the online DB:
A Database Error Occurred
Error Number: 1142
SELECT command denied to user 'user'#'49.32.197.240' for table 'answers'
SELECT *
FROM (`ibitstore`.`user`)
JOIN `english`.`answers`
ON `ibitstore`.`user`.`user_id` = `english`.`answers`.`user_id`
Filename: C:\xampp\htdocs\english\system\database\DB_driver.php
Line Number: 330
Please Help :(

You only have one connection to a database at a time. You'd have to run a query on one database, run a query on the second database and then manipulate the results of both within PHP.

You can run one SQL Query to be executed on two or more different databases. Containing tables of each.
How ever you can get the data from one database then use your own logic to merge them.

Related

Laravel count raw query always return zero

I am working with multiple databases in single project. When I run simple raw query to get another database table count but it always return zero instead of actual counts. Even I have more than 1 million records in table.
I run raw query in following formats but result is zero
$dbconn = \DB::connection("archive_db");
$dbconn->table('activities_archived')->count()
$sql = "SELECT COUNT(*) as total FROM activities_archived";
$result = \DB::connection("archive_db")->select(\DB::raw($sql));
Event I have set the database connections strict option to false but still facing same issue.
Now I am totaly stuck that why this issue is coming
$someModel->setConnection('mysql2');
$something = $someModel->count();
return $something;

Yii2- Not able to insert/delete rows using console controller

I am trying to implement email queue in my project which uses CRON.
I am adding a row in one table and deleting a row from another table using CreateCommand of yii2. Database is mysql.
The entire code is executed and it does not display any error. But the rows are not added or deleted from the database.
I have also tried doing the same thing using ActiveRecords but it does not work. Hence I have used CreateCommand.
Below is the code which I am using -
$connection = \Yii::$app->db;
$result = $connection->createCommand()->insert('email_queue_completed', $arrInsert)->execute();
if(!empty($result))
{
$connection->createCommand()
->delete('email_queue', ['id' => $mail->id])
->execute();
}
$arrInsert is an array containing key value pairs of values to be inserted.

MySQL/php: I created database and tables, when I try an INSERT I have #1146

I'm writing an installation script in php, this script has to ask the user some data and then store them in a XML file and on a database.
Here is the procedure:
1) Insert data;
2) Save configuration data (such as database name,user,password,host,port) in a XML file
3) Using those data to install a database (I have an empty dump I use to create it)
4) Insert in the "admin" table the first user data (taken from the form in point 1)
Now, everything works fine until point 4.
When I try to access the database MySql always returns my an error #1146 saying that the table doesn't not exists.
This is my custom JSON log:
{
"Status":"KO",
"Reason":"SELECT * FROM bbscp_admin_user; || Table 'adb.bbscp_admin_user' doesn't exist",
"Errno":1146
}
Obviously I checked both with phpMyAdmin and mysql (from cli) and I can say that both DB and Table DO exists.
Here is the part where I create the DB: [this works fine]
$Install = Install::getInstance();
$sqlscript = str_replace("__DBNAME__",
$config_info['dbname'],
file_get_contents('../config/bbscp-base-db.sql')
);
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_query($connection,'CREATE DATABASE '.$config_info['dbname'].';')){
echo 'Database successfully createad';
mysqli_close($connection);
}else{
die('ERROR CREATING DATABASE!');
}
Here the part where I populate the database from the dump (it only add the tables)
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd'],
$config_info['dbname']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_multi_query($connection, $sqlscript)){
echo 'Database successfully imported';
mysqli_close($connection);
}else{
die('ERROR IMPORTING DATABASE');
}
Now the decisive part, I open a connection with the database (using a library that I've developed in the past years and has always worked fine)
$DB = new Database(Install::getInstance());
$Q = new Query();
$DB->connect();
$query = $Q->addNewUser($config_info['nickname'],
$config_info['password'],
$config_info['firstname'],
$config_info['lastname'],
$config_info['email'],
0); // this just returns the query string I need
// the query in this case is:
// INSERT INTO bbscp_admin_user
// (nickname,password,firstname,lastname,mail,confirmed)
// VALUES (the ones above);"
$res=$DB->startQuery($query); // THIS IS WHERE THE ERROR IS RETURNED
// this function only wraps the mysqli_query and returns a custom JSON
I've tried a lot of solution.. The tables DO exists but every query I try to invoke at this point doesn't work because apparently "table doesn't exist" (even using mysqli function instead of mines).
Thanks in advance and sorry for the long question! :-)
EDIT 1
During this days I've changed a lot of code, I tried using different implementation using functions, objects, redirects but none of them seems to work.
The thing is always the same:
It creates the database
Returns the error code when trying to add the user
If I refresh the page it correctly adds the user

CodeIgniter Nested Query

I have a piece of code for getting conferences from database, where a specific subscriber is not subscribed.
I have two tables:
conferences - which holds all conferences
read - which holds subscriber with conferences
Here is the code, but I get MySQL 1064 error.
function getPossibleConferencesOfSubscriber($sub_id)
{
$a = "SELECT * FROM conference C where C.ISSN not in (SELECT ISSN FROM read where sub_id=$sub_id)";
$query = $this->db->query($a);
return $query->result();
}
Ok, I found the problem. I guess "read" is something like a command, so MySQL confuses the table name read and command read. I hope this helps someone, saves his 1 hour.

When using entity framework Where does this syntax return all records locally before doing the where

db.AdDetails.Where( u => u.OwnerGUID == CurrentUserProviderKey)
I have an adDetails table that has an OwnerGUID field.
I want to pull out only ad details that belong to the currenly logged in user.
My query does not show any where clauses in the SQL when I look at it in the debugger.
Can someone help me figure out what is wrong with my statement and if all rows in the table will be brought back then all 10K records put though a where on the webserver?
I am really new to this.
Using the Where extension method will filter down the results.
Queries in Entity Framweork are not executed until you iterate over them. If you do:
var query = db.Where(u => u.OwnerGUID == key);
This does not execute the query. When you do the following:
var list = list.ToList();
OR
foreach( var item in query) { ... }
That is when the query will be executed in SQL. The results should be filtered with your WHERE clause at this point.

Resources