I'm using codeigniter framework to develop one music cms. i have 3 tables in mysql database, Currently im working in "Album" Table and "Model, Controller". i want to SELECT "Album" Table 1 and JOIN "Album" -> "cat_id" with "Category" -> "cat_id", and fetch all categories records.
Then i want to JOIN "Album" -> "album_id" on "Soundtrack" -> "album_id" then fetch all soundtrack records A to Z.
Please somebody help me to show proper codeigniter query, how i can SELECT and JOIN Tables then fetch records from 3 tables, ?
Table 1 -> Category
cat_id
cat_name
cat_title
date
Table 2 -> Album
cat_id
album_id
album_title
album_details
Table 3 -> Soundtrack
album_id
track_title
track_url
date
Use this code in model
public function funcname($id)
{
$this->db->select('*');
$this->db->from('Album a');
$this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
$this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
$this->db->where('c.album_id',$id);
$this->db->order_by('c.track_title','asc');
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result_array();
}
else
{
return false;
}
}
try this
In your model
If u want get all album data use
function get_all_album_data() {
$this->db->select ( '*' );
$this->db->from ( 'Album' );
$this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
$this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
$query = $this->db->get ();
return $query->result ();
}
if u want to get specific album data use
function get_album_data($album_id) {
$this->db->select ( '*' );
$this->db->from ( 'Album' );
$this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
$this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
$this->db->where ( 'Album.album_id', $album_id);
$query = $this->db->get ();
return $query->result ();
}
Try this one for data...
function get_album_data() {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' )
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$query = $this->db->get ();
return $query->result ();
}
while for datum try this...
function get_album_datum($album_id) {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' )
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$this->db->where ( 'album.album_id', $album_id);
$query = $this->db->get ();
return $query->row();
}7
855788
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
Try as follows:
public function funcname($id)
{
$this->db->select('*');
$this->db->from('Album a');
$this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
$this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
$this->db->where('c.album_id',$id);
$this->db->order_by('c.track_title','asc');
$query = $this->db->get();
return $query->result_array();
}
If no result found CI returns false otherwise true
public function getdata(){
$this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
$this->db->from('tblmaster t');
$this->db->join('country c', 't.country=c.country_id');
$this->db->join('state s', 't.state=s.state_id');
$this->db->join('city ct', 't.city=ct.city_id');
$this->db->order_by('t.id','desc');
$query = $this->db->get();
return $query->result();
}
Related
I have 2 DQL queries
I want the user (with a select form) to be able to select:
1 filter at a time. Either party or city
or
several filters at the same time: party + city ... then others afterwards.
In summary :
In my database there are Party and City. With a form of select. The user must be able to choose the filters he wants. If he chose a particular Party without specifying the city, this will display all the Party in all the City. He can also choose a city, in which case he will have all the party of the chosen city. or 3rd case, he chose an Party + a City.
When one works the other is not.
I think I have a problem with my conditions and operators.
I read that using the orWhere () was bad practice.
Thanking you in advance.
public function searchByParty($party, $city)
{
$query = $this->createQueryBuilder('s');
$query = $query
->select( 'party', 'city', 's')
->join ('s.party', 'party ')
->join ('s.city', 'city');
if (!empty($party) === !empty($city)) {
$query = $query
->andWhere('party .id = :sport')
->andWhere('city.id = :city')
->setParameter('party ', $party )
->setParameter('city', $city);
}
if (!empty($party) && !empty($city)) {
$query = $query
->orWhere('party.id = :party')
->orWhere('city.id = :city')
->setParameter('party', $party )
->setParameter('city', $city);
}
return $query->getQuery()->getResult();
You have a logical issue. Your first if checks whether the existence of $party and $city is equivalent, which is true if and only if both exists or both does not exist. It does not make sense to check for their value if they both do not exist. The second if checks whether neither is defined. In that case it does not make sense to check the value against them. Fix:
public function searchByParty($party, $city) {
$query = $this->createQueryBuilder('s');
$query = $query
->select( 'party', 'city', 's')
->join ('s.party', 'party ')
->join ('s.city', 'city');
if (!empty($party)) {
$query = $query
->andWhere('party .id = :sport')
->setParameter('party ', $party )
}
if (!empty($city)) {
$query = $query
->andWhere('city.id = :city')
->setParameter('city', $city);
}
return $query->getQuery()->getResult();
}
EDIT: if you want to check whether any of them matches, then use orWhere:
public function searchByParty($party, $city) {
$query = $this->createQueryBuilder('s');
$query = $query
->select( 'party', 'city', 's')
->join ('s.party', 'party ')
->join ('s.city', 'city');
if (!empty($party)) {
$query = $query
->orWhere('party .id = :sport')
->setParameter('party ', $party )
}
if (!empty($city)) {
$query = $query
->orWhere('city.id = :city')
->setParameter('city', $city);
}
return $query->getQuery()->getResult();
}
Solution :
public function searchBySession($party, $city)
{
$query = $this->createQueryBuilder('s');
$query = $query
->select( 's');
if($party){
$query = $query
->join ('s.party', 'party')
->addSelect('party')
->andWhere('party.id = :party')
->setParameter('party', $party)
;
}
if($city){
$query = $query
->join ('s.city', 'city')
->addSelect('city')
->andWhere('city.id = :city')
->setParameter('city', $city)
;
}
return $query->getQuery()->getResult();
}
Thanks you
I'm working on Codeigniter rest API project and came across a problem. I would like my model to select additional data by condition.
if CATEGORY equals $CATEGORY show TYPE.TYPE_LABLE
otherwise just don't show "TYPE.TYPE_LABLE"
so how can i get this result?
thank you for your help.
function get_data() {
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
$CATEGORY = array('CATEGORY1', 'CATEGORY2', 'CATEGORY3', 'CATEGORY4');
$types = array('type_1', 'type_2');
if ($id != null) {
$this->db->where('ID',$id);
//selct TYPE.TYPE_LABLE if CATEGORY equals $CATEGORY
$this->db->select('POST.ID, POST.DATE, TYPE.Post_Type as P_TYPE, TYPE.TYPE_LABLE$CATEGORY', FALSE);
$this->db->join('TYPE', 'POST.TYPE_ID = TYPE.ID', 'left');
$this->db->join('CATEGORY', 'POST.CATEGORY_ID = CATEGORY.ID', 'left');
$this->db->order_by('POST.ID', 'DESC');
$this->db->where_in('POST.Post_Type', $types);
$this->db->where('POST.DATE >', date('Y-m-d', strtotime('01-01-2019')) );
$this->db->from('POST');
$result = $this->db->get();
}
return $result;
}
I have 3 tables guest_user_info,pg_company,user_profile.
In guest_user_info have 2 columns:
g_uid | company_id
In pg_company have 2 columns:
company_id | user_id
In user_profile have 2 columns:
id |user_email
Here i want to get user_email from user_profile.i have g_uid value (in guest_user_info table).i want company_id from guest_user_info and get the company_id and match with pg_company table,there i can get user_id.then match with that user_id with id in user_profile table.at last i need user_email from user_profile table
Well its a simple one, you just need to join using active query in CodeIgniter.
$this->db->select("UP.id", "UP.user_email");
$this->db->from("guest_user_info AS GU");
$this->db->join("pg_company AS PC", "PC.company_id=GU.company_id");
$this->db->join("user_profile AS UP", "UP.id=PC.user_id");
$this->db->where("GU.g_uid", $guid);
$query = $this->db->get();
return $query->result();
In above code, $guid you have to provide which you have.
Also please take a look at these links:
https://www.codeigniter.com/userguide3/database/query_builder.html
https://www.codeigniter.com/userguide2/database/active_record.html
You get so many things after reading this.
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'pg_company';
$join_str[0]['join_table_id'] = 'pg_company.company_id';
$join_str[0]['from_table_id'] = 'guest_user_info.company_id';
$join_str[0]['join_type'] = '';//set join type
$join_str[1]['table'] = 'user_profile';
$join_str[1]['join_table_id'] = 'user_profile.id';
$join_str[1]['from_table_id'] = 'guest_user_info.user_id';
$join_str[1]['join_type'] = '';
$selected ="guest_user_info.*,user_profile.user_name,pg_company.name";
$condition_array=array('guest_user_info.g_uid' => $g_uid);
$albumData= $this->common->select_data_by_condition('guest_user_info', $condition _array, $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
I wanting to be able to join two tables togeather.
How ever because I my forum table has column "name" and my forum_categories column "name"
I am not able to display both names.
On my select() if I use like $this->db->select('f.name, fc.name', false); it only displays name from forum_categories
array(1) { [0]=> array(1) { ["name"]=> string(17) "News & Discussion" } }
Question how can I get both names to show from both columns and
tables.
Note: I only want to be able to use $result['name'] in my foreach loop.
So the out put I would like it to be
General
News & Discussion
Lounge
I have looked at
CodeIgniter ActiveRecord field names in JOIN statement
codeigniter - select from 2 tables with same column name
Model
public function get_forums() {
$this->db->select('f.name, fc.name', false);
$this->db->from('forum as f');
// tried $this->db->join('forum_categories as fc', 'fc.forum_id = f.forum_id');
$this->db->join('forum_categories as fc', 'fc.forum_categories_id = f.forum_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
Controller
<?php
class Forums extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$data['label'] = '';
$data['forums'] = array();
$results = $this->get_forums();
var_dump($results);
if (isset($results)) {
foreach ($results as $result) {
$data['forums'][] = array(
'name' => $result['name'], // Only want to use single variable.
);
}
}
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('template/forum/list_forum_view', $data);
}
public function get_forums() {
$this->db->select('f.name, fc.name', false);
$this->db->from('forum as f');
$this->db->join('forum_categories as fc', 'fc.forum_categories_id = f.forum_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
}
update
works fine with code below but would rather just use one lot of join()
public function get_forums() {
$this->db->select("*");
$this->db->from('forum');
$query = $this->db->get();
foreach ($query->result_array() as $f) {
$data[] = array(
'name' => $f['name']
);
$this->db->select("*");
$this->db->from('forum_categories');
$query = $this->db->get();
foreach ($query->result_array() as $fc) {
$data[] = array(
'name' => $fc['name']
);
}
}
return $data;
}
Try This , It Will Work .
public function get_forums() {
$this->db->select('f.name as forum_name, fc.name as forum_categories_name', false);
$this->db->from('forum f');
// tried $this->db->join('forum_categories fc', 'fc.forum_id = f.forum_id');
$this->db->join('forum_categories fc', 'fc.forum_categories_id = f.forum_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
From what i see in your updated question. What you need is UNION and not JOIN. You can use get_compiled_select() to build both query before concat with UNION.
public function get_forums() {
$forum = $this->db->select('name')->get_compiled_select('forum');
$forum_categories = $this->db->select('name')->get_compiled_select('forum_categories');
$query = $this->db->query($forum.' UNION '.$forum_categories);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
Simply use
AS
keyword, because when you try to print it, that AS keyword give you optional name for your column.
Here i have two table which have same column name "name" so i have changed those with AS keyword.
Ex:
$this->db->select('tbl_category.id_category,tbl_category.name AS cat_name,
tbl_subject.id_subject,tbl_subject.name AS sub_name');
In result
Array ( [0] => Array ( [id_category] => 9 [cat_name] => OL [id_subject] => 13 [sub_name] => Science )
So it is simple solution from the SQL language
i first checked if there any same problems like mine i ddnt find anything.
all are sorting alphanumeric column mixed with numeric data.
here is my problem.
i have a table that contain column A datas like this.
WRG-01 WRG-39 WRG-22 WRG-45 WRG-43
need to sort that as
WRG-01 WRG-22 WRG-39 WRG-43 WRG-45
this is the code i using so far in codeigniter frame work
$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');
in mysql i can use this query to get done my work
preg_replace("/[^\d]/", "",'product_id'), 'asc')
How to apply it to my above codeigniter code?
here is search funtion
public function search()
{
$data['title'] = 'Search Product';
$product_name = $this->input->get('product_name');
$product_id = $this->input->get('product_id');
$product_category = $this->input->get('product_category');
$secondCategory = $this->input->get('secondCategory');
$thirdCategory = $this->input->get('thirdCategory');
$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
$data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
$data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}
if($product_name != '')
{
$this->db->like('product_name', $product_name);
}
if($product_id != '')
{
$this->db->where('product_id', $product_id);
}
if($product_category != '')
{
$this->db->where('product_category', $product_category);
}
if($secondCategory != '')
{
$this->db->where('secondCategory', $secondCategory);
}
if($thirdCategory != '')
{
$this->db->where('thirdCategory', $thirdCategory);
}
$data['products'] = $this->db->order_by('product_id' 'asc')->get('products');
theme('all_product', $data);
}
i can't use sql query here because products is result array from product table.
Use MySQL cast
cast(product_id as SIGNED)
or
cast(product_id as UNSIGNED)
Try query like that :-
select * from products cast(product_id as UNSIGNED) ASC|DESC
Try this
$query= $this->db->query("SELECT * FROM products WHERE ??==?? ORDER BY product_id ASC");
$result= $query->result_array();
return $result;
as default data will sort by Ascending Order
This is in model. So if you pass it to controller it will return data as Objective Array.
So in controller you can access
$result = $this->model_name->method_for_above_code();
$name = $result[0]['name'];
$id = $result[0]['id'];
if in View
$result['this_for_view'] = $this->model_name->method_for_above_code();
foreach ($this_for_view as $new_item) {
echo "Name is ".$new_item['name'];
echo "ID is ".$new_item['id'];
}