Joining tables from two databases using codeigniter - php

In order to write query in codeigniter you need to write something like $this->db->query or $someDB->query. But what if I want to join tables from two different databases?
I know that I can do it through pure php, using mysqli_connect and writing something like:
SELECT * FROM db1.table1 JOIN db2.table2
But is there a way to do it using codeigniter?

Use query method from CodeIgniter and pass any complex sql query trough:
$query = $this->db->query("SELECT * FROM dbname1.table t1 JOIN db2.table t2 ON t2.column = t1.column");
foreach ($query->result() as $row)
{
print_r($row);
}

This simple join of student and teacher table with same column name , Hope you will get it .
$this->db->select("s.*,t.*");
$this->db->from("student as s");
$this->db->join("teacher as t","s.student_id = t.student_id","both");
$result = $this->db->get()->result_array();
return $result;
also you want single row try row_array(); instead of result_array();

You can try to use the function I am using in a project I am working on right now... Please see the code below...
function join_table()
{
$this->db->select(//column name, //column name, //column name);
$this->db->from(//table1 name);
$this->db->join(//table2 name, //table1 name.//column name = //table2 name.//column name');
$this->db->where(//condition);
return $this->db->get()->result();
}

Related

Mysql two column Find one data in Rows using PHP

I have to try two joins but this is not going to work.
code in Codeginator.
$this->db->select('concat(firstName," ",lastName) as fullnameVisitor,users.firstName,visitorId,destinationId,count,activityStatus,created,updated');
$this->db->from('interestedprofile');
$this->db->join('users','users.userId=interestedprofile.visitorId','LEFT');
$this->db->join('users','users.userId=interestedprofile.destinationId','LEFT');
$this->db->join('interestedprofile','interestedprofile.destinationId=users.userId','LEFT');
$this->db->order_by('created','desc');
return $this->db->get()->result_array();
User Table : https://i.stack.imgur.com/ppM3s.png
Interest Table : https://i.stack.imgur.com/EbQIX.png
i have to find visitedid and destinationid users firstName and lastName in Users Table.
You don't have to use the Active Record fully to do the joins. You can use regular SQL. For example,
$query = $db->query("SELECT * FROM users;");
foreach ($query->getResult('User') as $user)
{
echo $user->name; // access attributes
echo $user->reverseName(); // or methods defined on the 'User' class
}
This Code is Work For me.
Select us1.firstName,us2.firstName from interestedprofile ip join users us1 on us1.userid = ip.visitorId join users us2 on us2.userId = ip.destinationId

Codeigniter cannot delete rows from database table using join method

I want to delete from ‘table1’ those rows where (user_id = 5) but I should check if those posts’ (title = title1 in table2). I use Codeigniter and I get this error while trying to delete: ‘Deletes are not allowed unless they contain a "where" or "like" clause.’ Could you please help me to check what is wrong with my code below.
table1:
table2:
public function delete($title, $user_id){
$this->db->select('table1.*');
$this->db->from('table1','table2');
$this->db->where('table1.user_id', $user_id);
$this->db->where('table2.title', $title);
$this->db->join('table2','table1.post_id=table2.post_id');
$query = $this->db->get();
if ($query && $query->num_rows() > 0) {
$this->db->delete('table1.*');
$this->db->from('table1','table2');
$this->db->where('table1.user_id', $user_id);
$this->db->where('table2.title', $title);
$this->db->join('table2','table1.post_id=table2.post_id');
return true;
}
else {
return false;
}
}
Make use of subqueries.
example
#Create where clause
$this->db->select('id');
$this->db->from('table2');
$this->db->where('table2.title', $title);
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->where('table1.user_id', $user_id);
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
$this->db->delete('table1');
References
stolen from here: https://stackoverflow.com/a/16303021/1275832
about subqueries: http://www.mysqltutorial.org/mysql-subquery/
compiled select: https://github.com/NTICompass/CodeIgniter-Subqueries
After running first query you will get the set of user that you have to delete.
Run this set throw foreach loop for getting id of user and posts that you have to delete to an array.
$user_array = array();
$post_array = array();
foreach($query->result() as $query)
{
$user_array[$query->user_id] = $query->user_id;
$post_user[$query->post_id] = $query->post_id;
}
And then
this->db->where_in('user_id', $user_array)->delete('table1');
this->db->where_in('post_id', $post_array)->delete('table2');
I know that this is not the best decision. But i think that this is the most understandable.
You may use the following code to delete data from tables becasue codeigniter ignore join when you delete multiple data from multiple tables.
$sql = "DELETE t1 FROM table1 t1
JOIN table2 t2 ON t1.thing_id = t2.id
WHERE t2.otherthing_id = ?";
$this->db->query($sql, array($id));
JOINS are used to fetch data from database not used to delete data if you want to delete data from multiple table using single query then you need to use cascading in MySQl using that you can delete data also from other tables that are related to current table.

Mysql - SELECT columns from 2 tables using INNER JOIN error

This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.

how to extract mysql data into json using php

i have retrieved mysql data from one table in json using the following script
$table_first = 'abc';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set = array();
$total_records = mysql_numrows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set[] = $link;
}
}
echo json_encode($set);
how can i retrieved data from two other tables in which there is a foreign key of this table in both of those tables. OR simply how can i retrieved data from 3 mysql tables in php.
I believe the best way to go here is using a JOIN or just something like this:
$sql = "SELECT
tabl1.*, table2.*, tabl3.* FROM table1, table2, table3
WHERE
table1.fk1 = table2.id AND
table1.fk2 = table2.id";
//Do the whole selection process...
If you make the queries separately, you'll be forcing 3 queries onto your database and will end in a performance hit that you dont need. So, the idea is load all the data from the DB using joins or similar that and then encode the results. Is faster and you'll leave the merging work to MySQL
Hope I can help
You can get all data firstly.
Then merge the data array.
Finally use json_encode to change the data format.
There is a foreign key of this table in both so you can use "join" to retrieve values from other tables.
Suppose that there are two tables as State(st_id,st_name) and City(ct_id,ct_name,state_id). Now, primary key are st_id & ct_id respectively of tables State & City.
Connection between this two table can be establish by joining State.st_id and City.state_id.
Now, coming to your problem to retrieve data from two table State & City, we can make sql query like following,
$sql="select s.*, c.* from State s, City c
where s.st_id=c.state_id ";
Using above query you can fetch data from database and convert into json format and can send it to android system. here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
I believe your code roughly will look like this:
$query = "SELECT
A.column1 AS First_1
A.column2 AS First_2
B.column2 AS Second
C.column3 AS Third
FROM table1 A, table2 B, table3 C
WHERE
A.fk1 = B.id AND
B.fk2 = C.id";
where a column is a relevant record you want to show. Meanwhile,
AS will act as a key name in JSON.

how to get data from three tables by a join statement in mysql

In my application i have three tables, reservation, patient and sub_unit, i need to take the patient_id from reservation table and query the patient table for patient data,same time i need to take the sub_unit_id from the reservation table and query the sub_unit name from the sub_unit table... i need to put all this data in to an one array in the sequence like
patient_id, sub_unit_name, patient_name, address and pass it to the Codeigniter table class to draw a table.
How can I query three tables in the same time to query out this data? can you guys help me out?
Using code igniter syntax it can be done as follows -
$this->db->select('r.patient_id, s.sub_unit_name, p.patient_name, p.address');
$this->db->from('reservation r');
$this->db->join('patient p', 'p.id = r.patient_id');
$this->db->join('sub_unit s', 's.id = r.sub_unit_id');
$query = $this->db->get();
You can check your formed query by -
echo $this->db->_compile_select();exit;
Select r.patient_id, s.sub_unit_name, p.patient_name, p.address
from reservation r, sub_unit s, patient p
where r.patient_id = p.patient_id and r.sub_unit_id = s.sub_unit_id
The join syntax is very straightforward in SQL. You are probably looking for something like this:
SELECT reservation.patient_id,
sub_unit.sub_unit_name,
patient.patient_name,
patient.address
FROM reservation
JOIN patient ON (patient.id = reservation.patient_id)
JOIN sub_unit ON (sub_unit.id = reservation.sub_unit_id);
In MySQL, the default join is an Inner Join, which I think is what you're looking for. You may also want to look into Outer Joins which are also very useful.
it worked guys , i did it like this using Codeigniter active records ,hope you guys can use it too
function get_data(){
$sql = 'SELECT * FROM visit,patient,sub_unit WHERE visit.patient_patient_id = patient.patient_id AND visit.sub_unit_sub_unit_id = sub_unit.sub_unit_id';
$this->db->order_by("reference_number", "desc");
$query = $this->db->query($sql);
return $query;
}
thanx for all your support!

Categories