How to join 2 tables in codeigniter PHP? - codeigniter

I have 2 tables guest_info and guest_profile.two columns are there g_uid and company_id.Based on company_id(I have companyID), i have to take all g_uid.
In guest_info table,
g_uid | companyID
1 5
2 5
3 6
In guest_profile table,display all values from this table(only need to display first two datas)
g_uid | fname
1 xyz
2 fds
3 fsdf

Go to folder "Models" That´s where you´ll do all your CRUD operations to the database.
For example, you can create a model file called "guest_profile_model.php"
Now you open that file and paste the code bellow:
<?php
class guest_profile_model extends CI_Model {
public function select($company_id) {
$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");
$result = $this->db->query($query);
return $result->result_object();
}
}
That´s it, now from within your controller you just need to load and call it.
Example:
$this-> load-> model('guest_profile_model ');
$company_id = 1;
$queryResult = $this -> guest_profile_model ->select(company_id);
print_r($queryResult);
Notice that the query return is going to be an object, that is because of the "result_object" in the model, you can change that to be an array if you want to.

//Try this sql query to join 2 table in codeigniter
$company_id = 5;
$this->db->query("select * from `guest_info` INNER JOIN `guest_profile` ON guest_info.g_uid = guest_profile.g_uid WHERE guest_info.company_id = ".$company_id." LIMIT 2");

$this->db->select('*');
$this->db->from('Table1 AS a');
$this->db->join('Table2 AS b', 'a.id = c.id', 'LEFT');
$this->db->join('Table3 AS c', 'a.name = c.name', 'LEFT');
$result = $this->db->get();
hopefully you get my example.
More info : https://www.codeigniter.com/userguide3/database/query_builder.html?highlight=joins#selecting-data

Related

laravel eloquent union, join 2 columns in the same table

I have the following columns in the same table
Column 1
--------
1
2
3
Column 2
--------
4
5
6
I want it to be displayed like
Columns
--------
1
2
3
4
5
6
You can use unionAll
$first = DB::table('yourTable')
->select('column1 as res');
$result = DB::table('yourTable')
->select('column2 as res')
->unionAll($first)
->get();
You can make the Union of your data by taking out separately and merge it after. You can use union() as well as merge(), One thing to mention is that both data must have same skelton means structure.
use DB;
public function yourFunction(){
$data_1 = DB::table('table_name')->get();
$data_2 = DB::table('table_name')->get();
//your final data
$final_data = $data_1->union($data_2);
}
Assuming values are in the same row:
$data = DB::table('table_name')->select('column1', 'column2')->get();
$c = count($data);
if ($c) {
$col1 = [];
$col2 = [];
foreach ($data as $k => $d) {
$col1[] = $d->column1;
$col2[$c + $k] = $d->column2;
}
$result = array_merge($col1, $col2);
foreach ($result as $value) {
echo $value."\n";
}
} else {
echo "No data in table.";
}

Left join not working in codeigniter

I written query to get record from main table tpl_upload_csv_file and get related record from tbl_process_csv. I get all the records but the problem is if i have 1 id from tpl_upload_csv_file in tbl_process_csv for 5 rows its displaying 5 times. Same record is displaying 5 times.
$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
print_r($query->result());die;
return $query->result();
My table structure is
tpl_upload_csv_file :
id
uploaded_file_name
uploaded_date_time
records_available
tbl_process_csv :
id
csv_file_id -->(Reference if for table tpl_upload_csv_file)
record_no
process_status
reason
Try this and let me know if any problem occur:
$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->group_by('tbl_process_csv.csv_file_id');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
return $query->result();
$this->db->distinct('tbl_process_csv.id');
Add this line in your code.
So, you will get distinct records w.r.t tbl_process_csv.id

2 join conditions codeigniter giving error

I have 2 tables - for orders and for documents for these orders. I want to show all orders from first table and if there are documents for these orders, to show date of documents(I take date from table documents).
I'm trying to make 2 join conditions because in table documents if I only join on idOrder, there are more than 1 row and I have to join on documents.name to be same as $this->uri->segment(3).
But I'm using the following code and it gives me error. Could I use 2 join conditions in this way:
My model is:
<?php
public function get_all_orders($user_id){
$this->db->select('ordersheader.*, customer.name as customerName,documents.date_make');
$this->db->from('ordersheader');
$this->db->join('customer', 'ordersheader.idCustomer = customer.idCustomer');
$this->db->join('documents', 'ordersheader.idOrder = documents.idOrder','left');
$this->db->join('documents as D', 'D.name="declaration"','left');
$this->db->where('ordersheader.user_id', $user_id);
$query = $this->db->get();
return $query->result_array();
}
Edited: I found solution. But it's written in pure sql, how to write it with Codeingiter syntax? My new working code is:
<?php
$query=("SELECT ordersheader.*, customer.name as customerName,documents.date_make,documents.deactivated_at
FROM ordersheader JOIN customer ON ordersheader.idCustomer = customer.idCustomer
LEFT JOIN documents
ON ordersheader.idOrder = documents.idOrder AND documents.name = '".$document."'
WHERE ordersheader.user_id = '".$user_id."' ");
$result = $this->db->query($query);
return $result->result_array();
This is wrong in your query
$this->db->join('documents as D', 'D.name="declaration"','left');
you can compare column using where clause
public function get_all_orders($user_id){
$this->db->select('ordersheader.*, customer.name as customerName,documents.date_make');
$this->db->from('ordersheader');
$this->db->join('customer', 'ordersheader.idCustomer = customer.idCustomer');
$this->db->join('documents', 'ordersheader.idOrder = documents.idOrder','left');
// $this->db->join('documents as D', 'D.name="declaration"','left'); / comment this line
$this->db->where('documents.name', 'declaration');
$this->db->where('ordersheader.user_id', $user_id);
$query = $this->db->get();
return $query->result_array();
}

writing the query in codeigniter giving a different result than required

I am working on codeigniter and I am writing the following query:
$this->db->select('*');
$this->db->from('tbl_profile');
$this->db->join('tbl_msg', 'tbl_msg.msg_sender_id = tbl_profile.profile_id');
$this->db->order_by("msg_id", "desc");
$query = $this->db->get('', $config['per_page'], $this->uri->segment(3));
$data['records'] = $query->result_array();
Correspondingly I am getting the following result:
SELECT (*) FROM tbl_profile
JOIN tbl_msg ON tbl_msg.msg_sender_id = tbl_profile.profile_id
Which is returninng a wrong result as I want the result corresponding to the following query:
select * from tbl_profile as A
join (select * from tbl_msg) as B on A.profile_id = B.msg_sender_id
Please help
First of all, you missing the order by clause, but I assum, you mean other differences.
If you want that, you can use this query, what will gave you back the exact code:
$this->db->select('*', FALSE);
$this->db->from('tbl_profile as A');
$this->db->join('( select * from tbl_msg ) as B', 'A.msg_sender_id = B.profile_id');
$this->db->order_by("msg_id", "desc");
$query = $this->db->get('', $config['per_page'], $this->uri->segment(3));
$data['records'] = $query->result_array();
From codeigniter user manual:
$this->db->select()
accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.

Codeigniter: Select from multiple tables

How can I select rows from two or more tables?
I'm setting default fields for a form, and I need values from two tables...
My current code reads:
$this->CI->db->select('*');
$this->CI->db->from('user_profiles');
$this->CI->db->where('user_id' , $id);
$user = $this->CI->db->get();
$user = $user->row_array();
$this->CI->validation->set_default_value($user);
The example in the User Guide should explain this:
$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id
See the whole thing under Active Record page in the User Guide.
Just add the other table to the "->from()" method. Something like:
$this->db->select('t1.field, t2.field2')
->from('table1 AS t1, table2 AS t2')
->where('t1.id = t2.table1_id')
->where('t1.user_id', $user_id);
I think the question was not so much about joins as how to display values from two different tables - the User Guide doesn't seem to explain this.
Here's my take:
$this->db->select('u.*, c.company, r.description');
$this->db->from('users u, company c, roles r');
$this->db->where('c.id = u.id_company');
$this->db->where('r.permissions = u.permissions');
$query = $this->db->get();
I think the syntax is incorrect.
You need to select one record. I have two tables, and I have an id from one table transfer by parameter, and the relation of both tables.
Try this
$this->db->select('*')
->from('student')
->where('student.roll_no',$id)
->join('student_details','student_details.roll_no = student.roll_no')
->join('course_details','course_details.roll_no = student.roll_no');
$query = $this->db->get();
return $query->row_array();
$SqlInfo="select a.name, b.data fromtable1 a, table2 b where a.id=b.a_id";
$query = $this->db->query($SqlInfo);
try this way, you can add a third table named as c and add an 'and' command to the sql command.
// Select From Table 1 All Fields, and From Table 2 one Field or more ....
$this->db->select('table1.*, table2.name');
$this->db->from('table1, table2');
$this->db->where('table2.category_id = table1.id');
$this->db->where('table2.lang_id',$id); // your where with variable
$query = $this->db->get();
return $query->result();

Resources