CodeIgniter/PHP/MySQL: Retrieving data with JOIN - php

I'm new to PHP/MySQL and super-new to CodeIgniter..
I have information in many MySQL tables. I want to retrieve it with JOIN where the tables primary keys are equal to $variable... How can I do it and get all the fields without the primary key field???
What I'm doing now is this (only two tables joined here):
function getAll($id) {
$this->db->select('*');
$this->db->from('movies');
$this->db->join('posters', 'movies.id= posters.id');
// WHERE id = $id ... goes here somehow...
$q = $this->db->get();
if ($q->num_rows() == 1) {
$row = $q->row();
$data = array(
'id' => $row->id,
'title' => $row->title,
'year' => $row->year,
'runtime' => $row->runtime,
'plotoutline' => $row->plotoutline,
'poster_url' => $row->poster_url
);
}
$q->free_result();
return $data;
id (PK), title, year, runtime and plotoutline are columns from the first table and poster_url is a field from the second table. The second table also contains an ID (PK) column that I don't want to Retrieve because I already have.

Jon is right. Here's an example:
$this->db->select('movies.id,
movies.title,
movies.year,
movies.runtime as totaltime,
posters.poster_url');
$this->db->from('movies');
$this->db->join('posters', 'movies.id= posters.id');
$this->db->where('movies.id', $id);
$q = $this->db->get();
This will return objects that have ->id, ->title, ->year, ->totaltime, and ->poster_url properties. You won't need the additional code to fetch the data from each row.
Don't forget, if the Active Record syntax gets a little unwieldy, you can use full SQL queries and get the same results:
$sql = "SELECT movies.id,
movies.title,
movies.year,
movies.runtime as totaltime,
posters.poster_url
FROM movies
INNER JOIN posters ON movies.id = posters.id
WHERE movies.id = ?"
return $this->db->query($sql, array($id))->result();
Both forms will ensure that your data is escaped properly.
CodeIgniter Active Record
Query Binding in CodeIgniter

An asterisk will return all the fields. To return a subset of these, i.e. all fields apart form the repeated id field, simply list the columns which you require rather than use '*'.
It is often a good idea to not use asterisk anyway. In the future of the app, someone may add a large field to the table which will be surplus to your requirements, and will slow your queries.

Simply put with method chaining:
$this->db->select('*')
->from('movies')
->join('posters', 'movies.id= posters.id')
->where('movies.id', $id)
->get();

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

Related

Codeigniter 3 joining 2/3 tables

I'm using Codeigniter and I need to join 2/3 tables. I can't quite work it out.
I have a users table with general user info.
user_id
first_name
last_name
I have a course stats page with info like due date etc.
id
course_id
user_id
due
completed_on
A user will pick a course, and then be presented with a list of users of their organization. Ready to be assigned. The user may already be assigned to the course and have stats in the stats table while other users may not have stats.
So I need to display a list of users with any stats to the chosen course, if the stats do of course exists.
SO, I'm sending to the model an org_id (to get a list of users of that org) and the chosen course_id (to retrieve any stats from he stats table if they exist)
Here's my method in the model
// get users for an org along with stats
public function get_course_user_data($org_id,$course_id) {
$user_array = array('users.org_id =' => $org_id);
$this->db->select('users.id,users.first_name,users.last_name,training_stats.due,training_stats.completed_on');
$this->db->order_by('users.first_name', 'asc');
$this->db->where($user_array);
$this->db->join('training_stats','training_stats.user_id = users.id', 'left');
$this->db->join('training_courses','training_courses.course_id = training_stats.course_id', 'left');
$user_object = $this->db->get('users');
return $user_object->result();
}
At the moment, if there are stats in the stats table then it displays data, if there are no stats in the stats table, I get nothing.
But I need a full list of users and only the stats if they exist.
Can I even do this with a join? I would have though so?
Try this query:
// get users for an org along with stats
public function get_course_user_data($org_id,$course_id) {
$this->db->select('users.id,users.first_name,users.last_name,training_stats.due,training_stats.completed_on');
$this->db->order_by('users.first_name', 'asc');
$this->db->join('training_stats','training_stats.user_id = users.id', 'left');
$this->db->join('training_courses','training_courses.course_id = training_stats.course_id', 'left');
$this->db->where("( training_courses.course_id = $course_id AND training_stats.course_id = $course_id)" );
$this->db->or_where( "( users.org_id = $org_id )" );
$user_object = $this->db->get('users');
return $user_object->result();
}
I think you forgot something...
$this->db->from('table_name');
after this....
$this->db->select('users.id,users.first_name,users.last_name,training_stats.due,training_stats.completed_on');
I hope this help

Query for getting values from multiple tables

I have a table video with fields videoid, genre(int-foreign key), language(int-foreign key) etc. I want to get the value of genre from genre table and language from movie_languages table.
The structure of tables are given below:
video
genre
movie_languages
How can I join these 3 tables to get the language and genre related to each videos in video table. Also when user didn't select genre/language in the form, value 0 will be inserted to the table. Will this affect the query. I am using codeingiter and I tried with the following query and is not working.
$this->db->select('video.*,movie_languages.language,genre.genre');
$this->db->join('genre', 'video.genre = genre.id');
$this->db->join('movie_languages', 'video.language = movie_languages.id');
$query = $this->db->get();
Please help me.
Thanks in advance.
It will be, you need a left join in this case
Try this
$query = $this->db
->select('v.*,ml.language,g.genre')
->from('video as v')
->join('movie_languages AS ml', 'v.language = ml.id', 'left outer')
->join('genre AS g', 'v.genre = g.id', 'left outer')
->get();
try this
$this->db->select('video.*,movie_languages.language,genre.genre')
->from('video')
->join('genre', 'video.genre = genre.id')
->join('movie_languages', 'video.language = movie_languages.id');
$query = $this->db->get();

Retrieving multiple values associated with a single record. MySQL PHP Codeigniter

I need help with a query on following tables.
table user(
user_id char(5),
username char(12),
columnx char(10));*
table phone(
user_id char(5),
phone_number number(10),
primary(Y, N) char(1));*
Both tables linked on user_id,
Here each user can have multiple phone_numbers.
I need to pullout a set of users and along with their phone numbers. I am trying to do the following.
in model
$this->db->where('columnx', 'something');
$query = $this->db->get('users');
foreach($query->result() as $row) {
$this->db->select('phone_number');
$this->db->where('user_id', $row->user_id);
$this->db->where('primary', 'Y');
$q = $this->db->get('phone');
}
How do I return from model and display multiple phone number for each user, when I my first $query returns multiple users??
Thanks in advance,
Prim
Try using join:
$query = $this->db->select('*')
->from('user as a')
->join('phone as b', 'a.user_id = a.user_id')
->where(array('a.columnx' => 'something'));
->get();
var_dump($query->result());

CodeIgniter PHP - How to choose which ID to select in a join while using "select *"

Basically, I've got this coding convention that any primary key which is an ID, I will call the column name "id". So here comes my problem. I'm joining two tables and I'm getting the ID of the second table instead of the first table. I know if I use select "artists.id, ..." it will work, but I want to know if there's a fix with using "select *" which would be better for future expansion (new colums will come ...).
Here's my model:
$this->db->select('*');
$this->db->from('artists');
$this->db->join('categories', 'artists.category_id = categories.id');
$this->db->where('id', $id);
$this->db->limit(1);
With Print_R I can see I'm getting all columns (but only 1 id, which is from the categories table instead of artists table) without any table prefix.
You should qualify your columns with a table alias
$this->db->select('a.id as artist_id, c.id as category_id, a.column2,c.column3');
$this->db->from('artists a');
$this->db->join('categories c', 'a.category_id = c.categories.id');
$this->db->where('a.id', $id);
$this->db->limit(1);
If you want to continue using SELECT *
$this->db->select('a.*, c.*, a.id as artist_id, c.id as category_id');
$this->db->from('artists a');
$this->db->join('categories c', 'a.category_id = c.categories.id');
$this->db->where('a.id', $id);
$this->db->limit(1);
Keep in mind, that the LAST duplicate column will be returned. So, a.*,c.* will return c.id as id and c.*,a.* will return a.id as id.
I think to save you trouble and for the future, always use the table in front of the column name.
There is no logic here, when you look for * it means all fields, in Oracle for example you will get all fields with the table in front, i guess in MySQL it doesn't, but if i were you, i would not risk it.

codeigniter join 2 table data

hi everyone i am new to codeigniter and currently working on a small project in the project i am trying to join two tables and display there data in single table. i looked at the user guide that codeigniter has an i am not sure how this work
$this->db->join();
what table should be first and what id key should be firs. Can someone explain me more in detail about this please use examples if u can. I am trying to join credential table and tblanswers. Tnx for answering.
i have tried to code a function using this example:
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
EDIT:
instead of using join method in codeigniter is it possible to use a simple function to retrieve the two table data separately? all i want is to echo the data from database table on to a html table in my website page to be displayed is it possible to write two get functions to retrieve two tables separately ?
It doesn't matter what table is first... Simply:
<?php
$this->db->select('t1.name, t2.something, t3.another')
->from('table1 as t1')
->where('t1.id', $id)
->join('table2 as t2', 't1.id = t2.id', 'LEFT')
->join('table3 as t3', 't1.id = t3.id', 'LEFT')
->get();
?>
here is how it works:
suppose we have two tables namely student, library.
note: but remember that one of the column should match if you want to use where condition/ here we assume that both tables have std_id column
Write the the select query as follows, in the brackets write what are all the things you want
note:write as shown below don't put quotes to each single one put it on whole at once.
*note: suppose we want name, phone_no. from student table and book_name form library table.*
$this->db->select('name, phone_number, book_name');
Now write the from query and write one of the table name(No rule)
$this->db->from('student');
Now join this with the another table with join query
$this->db->join('library', 'students.std_id=library_std_id');
Now write the where condition that like you want book name form library table where std id=1(in practical you need to fetch this id from view/database)
$this->db->where('std_id', 1);
$q= $this->db->get();
That's it it's done now you can print and check the result.
$this->db->join('comments', 'comments.id = blogs.id');
With this line you tell: search me inside comments all comments with id equal blogs.id.
Usually is something like that I think:
$this->db->join('comments', 'comments.blogs_id = blogs.id');
You have to insert into your table a field named blogs_id (int value unisgned) because blogs can have more comments.
Isn't important the position of first or second value
Hi this will work for joining two tables in codeIgnator.
$this->db->select("chat.id,chat.name,chat.email,chat.phone,chat.date,post.post");
$this->db->from('chat');
$this->db->join('post', 'chat.id = post.id');
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result();
}
else
{
return false;
}
You can change to the query as you like do trail and error method to get your appropriate results.
This is my code for joint many tables as possible.
I have 3 tables professeurs,publications and support.
public function toutesdonnées(){
$this->db->select("*");
$this->db->from('publication');
$this->db->join('support', 'publication.idsup = support.idsup');
$this->db->join('professeurs', 'publication.emailprof = professeurs.emailprof');
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result();
}
else
{
return false;
}

Categories