Sql Combining AND with OR in codeigniter - php

I want To combine AND condition with OR condition in codeigniter SQL query
i am creating a where condition depending on the users input.
when a user select rent, iam passing OR condition inside WHERE(AND) like this $where['p.contract_id = 3 OR p.contract_id']=2;.
here is my code..
$where = array('p.status' => 1, 'pi.order' => 1);
if(!$fil['city'] == 0){
$where['p.city_id']=$fil['city'];
}
if(!$fil['area'] == 0){
$where['p.area_id']=$fil['area'];
}
if(!$fil['type'] == 0){
$where['p.type_id']=$fil['type'];
}
if(!$fil['bed'] == 0 && !$fil['bed']== 10){
$where['pd.bed']=$fil['bed'];
}
if($fil['bed']== 10){
$where['pd.bed >']=$fil['bed'];
}
if(!$fil['bath'] == 0 && !$fil['bath'] == 10){
$where['pd.bath']=$fil['bath'];
}
if($fil['bath'] == 10){
$where['pd.bath >']=$fil['bath'];
}
if(!is_null($fil['rent'])){
$where['p.contract_id = 3 OR p.contract_id']=2;
}
if(!is_null($fil['sale'])){
$where['p.contract_id']=1;
}
if(!$fil['price_from'] ==""){
$where['pd.price >']=$fil['price_from'];
}
//real query
$this->db->select('p.*, pd.title, pd.price, pd.bed, pd.bath, pd.size, pd.size_type, pd.full_description,
pi.name as image, pi.order, a.name as area, t.name as type_name, ct.name as contract_type, pv.views as views,
c.name as city');
$this->db->from('property p');
$this->db->join('property_detail pd', 'pd.property_id=p.property_id', 'left');
$this->db->join('property_image pi', 'pi.property_id=p.property_id', 'left');
$this->db->join('type t', 't.type_id=p.type_id', 'left');
$this->db->join('contract_type ct', 'ct.con_typ_id=p.contract_id', 'left');
$this->db->join('property_views pv', 'pv.property_id=p.property_id', 'left');
$this->db->join('area a', 'a.area_id=p.area_id', 'left');
$this->db->join('city c', 'c.city_id=p.city_id', 'left');
$this->db->where($where);
$this->db->order_by('p.property_id','desc');
$this->db->limit($config['per_page'], $this->uri->segment(3));
$query = $this->db->get();
$result = $query->result();
return $result;
ERROR
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2' at line 12
SELECT 'p'.*,
'pd'.'title',
'pd'.'price',
'pd'.'bed',
'pd'.'bath',
'pd'.'size',
'pd'.'size_type',
'pd'.'full_description',
'pi'.'NAME' AS 'image',
'pi'.'ORDER',
'a'.'NAME' AS 'area',
't'.'NAME' AS 'type_name',
'ct'.'NAME' AS 'contract_type',
'pv'.'views' AS 'views',
'c'.'NAME' AS 'city'
FROM 'property' 'p'
LEFT JOIN 'property_detail' 'pd'
ON 'pd'.'property_id'='p'.'property_id'
LEFT JOIN 'property_image' 'pi'
ON 'pi'.'property_id'='p'.'property_id'
LEFT JOIN 'type' 't'
ON 't'.'type_id'='p'.'type_id'
LEFT JOIN 'contract_type' 'ct'
ON 'ct'.'con_typ_id'='p'.'contract_id'
LEFT JOIN 'property_views' 'pv'
ON 'pv'.'property_id'='p'.'property_id'
LEFT JOIN 'area' 'a'
ON 'a'.'area_id'='p'.'area_id'
LEFT JOIN 'city' 'c'
ON 'c'.'city_id'='p'.'city_id'
WHERE 'p'.'status' = 1
AND 'pi'.'ORDER' = 1
AND 'p'.'contract_id' = 3
OR p.contract_id 2
i Know very Well this error is Caused because if this $where['p.contract_id = 3 OR p.contract_id']=2;. Can some one help me to pass this where condition with OR statement in codeigniter. Tnx..

This might work for you. Here I've placed or_where() and where() after where condition which checks for your if condition
$this->db->distinct();
$this->db->select('p.*, pd.title, pd.price, pd.bed, pd.bath, pd.size, pd.size_type, pd.full_description,
pi.name as image, pi.order, a.name as area, t.name as type_name, ct.name as contract_type, pv.views as views,
c.name as city',false);
$this->db->from('property p');
$this->db->join('property_detail pd', 'pd.property_id=p.property_id', 'left');
$this->db->join('property_image pi', 'pi.property_id=p.property_id', 'left');
$this->db->join('type t', 't.type_id=p.type_id', 'left');
$this->db->join('contract_type ct', 'ct.con_typ_id=p.contract_id', 'left');
$this->db->join('property_views pv', 'pv.property_id=p.property_id', 'left');
$this->db->join('area a', 'a.area_id=p.area_id', 'left');
$this->db->join('city c', 'c.city_id=p.city_id', 'left');
$this->db->where($where);
if(!is_null($fil['rent'])){
$this->db->where('p.contract_id','3');
$this->db->or_where('p.contract_id','2');
}
$this->db->order_by('p.property_id','desc');
$this->db->limit($config['per_page'], $this->uri->segment(3));
$query = $this->db->get();
$result = $query->result();
return $result;
Output
SELECT `p`.*, `pd`.`title`, `pd`.`price`, `pd`.`bed`, `pd`.`bath`, `pd`.`size`, `pd`.`size_type`, `pd`.`full_description`, `pi`.`name` as image, `pi`.`order`, `a`.`name` as area, `t`.`name` as type_name, `ct`.`name` as contract_type, `pv`.`views` as views, `c`.`name` as city FROM (`property` p) LEFT JOIN `property_detail` pd ON `pd`.`property_id`=`p`.`property_id` LEFT JOIN `property_image` pi ON `pi`.`property_id`=`p`.`property_id` LEFT JOIN `type` t ON `t`.`type_id`=`p`.`type_id` LEFT JOIN `contract_type` ct ON `ct`.`con_typ_id`=`p`.`contract_id` LEFT JOIN `property_views` pv ON `pv`.`property_id`=`p`.`property_id` LEFT JOIN `area` a ON `a`.`area_id`=`p`.`area_id` LEFT JOIN `city` c ON `c`.`city_id`=`p`.`city_id` WHERE `p`.`status` = 1 AND `pi`.`order` = 1 AND `p`.`contract_id` = '3' OR `p`.`contract_id` = '2' ORDER BY `p`.`property_id` desc LIMIT 0

You can try something like that:
$this->db->where('(p.contract_id = 3 OR p.contract_id =2) AND (...) ', NULL, FALSE);
The third parameter tells ci that it should not try to protect your field names. You will have to care yourself for injection problems.

SELECT `p`.*, `pd`.`title`, `pd`.`price`, `pd`.`bed`, `pd`.`bath`, `pd`.`size`, `pd`.`size_type`, `pd`.`full_description`, `pi`.`name` as `image`, `pi`.`order`, `a`.`name` as `area`, `t`.`name` as `type_name`, `ct`.`name` as `contract_type`, `pv`.`views` as `views`, `c`.`name` as `city` FROM `property` `p` LEFT JOIN `property_detail` `pd` ON `pd`.`property_id`=`p`.`property_id` LEFT JOIN `property_image` `pi` ON `pi`.`property_id`=`p`.`property_id` LEFT JOIN `type` `t` ON `t`.`type_id`=`p`.`type_id` LEFT JOIN `contract_type` `ct` ON `ct`.`con_typ_id`=`p`.`contract_id` LEFT JOIN `property_views` `pv` ON `pv`.`property_id`=`p`.`property_id` LEFT JOIN `area` `a` ON `a`.`area_id`=`p`.`area_id` LEFT JOIN `city` `c` ON `c`.`city_id`=`p`.`city_id`
WHERE `p`.`contract_id` IN ('3', '2') AND `p`.`status` = 1 AND `pi`.`order` = 1 ;

Related

Error Number: 1054 Unknown column '2021-08-23' in 'on clause'

I have join many tables in this query via LEFT JOIN and i want to apply condition on table but php is giving me following error
Error Number: 1054 Unknown column '2021-08-23' in 'on clause'
SELECT i.isn_Add_Date, s.scentre_Name, i.isn_Job_No,cp.cpart_Part_Id,
cp.cpart_Part,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount,
p.product_Name,m.model_Name,c.complaint_Job_No,c.complaint_Add_Date,
c.complaint_Under_Warranty,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount
FROM complaints as c LEFT JOIN complaint_parts as cp ON c.complaint_Id
= cp.cpart_Complaint_Id LEFT JOIN scentres as s ON s.scentre_Id = c.complaint_Scentre_Id LEFT JOIN products as p ON p.product_Id =
c.complaint_Product_Id LEFT JOIN models as m ON m.model_Id =
c.complaint_Model_Id LEFT JOIN isn as i ON i.isn_Complain_Number =
c.complaint_Job_No AND i.isn_Add_Date BETWEEN '2021-08-23' AND
'2021-08-26' WHERE c.complaint_Scentre_Id = '1' AND c.complaint_Status
= 'Delivered' AND c.complaint_Trash = 0
here is my php code
$this->db->select('i.isn_Add_Date,s.scentre_Name,i.isn_Job_No,cp.cpart_Part_Id,cp.cpart_Part,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount,p.product_Name,m.model_Name,c.complaint_Job_No,c.complaint_Add_Date,c.complaint_Under_Warranty,cp.cpart_Qty,cp.cpart_Rate,cp.cpart_Amount');
$this->db->join('complaint_parts as cp', 'c.complaint_Id = cp.cpart_Complaint_Id ', 'left');
$this->db->join('scentres as s', 's.scentre_Id = c.complaint_Scentre_Id', 'left');
$this->db->join('products as p', 'p.product_Id = c.complaint_Product_Id', 'left');
$this->db->join('models as m', 'm.model_Id = c.complaint_Model_Id', 'left');
$this->db->JOIN('isn as i', 'i.isn_Complain_Number = c.complaint_Job_No AND i.isn_Add_Date BETWEEN '.str_replace('/', '-', $fromDate).' AND '.str_replace('/', '-', $toDate).'', 'LEFT');
$this->db->where("c.complaint_Scentre_Id", $serviceCenterId[0]);
$this->db->where("c.complaint_Status",'Delivered');
$this->db->where("c.complaint_Trash", 0);
$query = $this->db->get("complaints as c");
change
`2021-08-23` AND `2021-08-26`
to
'2021-08-23' AND '2021-08-26'
as the ` character implies columns and not strings
the sql is ok
maybe the orm can not handle complex join condition
you can move the join condition 【AND i.isn_Add_Date BETWEEN '2021-08-23' AND '2021-08-26'】 to where condition
just like $this->db->where("i.isn_Add_Date", BETWEEN ,['2021-08-23','2021-08-26]);

mysql query to check a field exist in an array in codeigniter

I post an array of skills from the form and i need to fetch list of candidates list related to the elements in array in codeigniter.
Controller
$data = array(
"mode" => $this->input->post("mode"),
"designation" => $this->input->post("designation"),
"notice_period" => $this->input->post("notice_period"),
"skill" => $this->input->post("skills"),
"cities" => $this->input->post("city")
);
$this->load->model("search_model");
$this->load->model("candidate_model");
$data["candidate"] = $this->search_model->fetch_candidate($data);
$data["designation"] = $this->candidate_model->fetch_designation();
$this->load->view('candidate_profiles', $data);
model
function fetch_candidate($data)
{
$mode = $data['mode'];
$designation = $data['designation'];
$notice_period = $data['notice_period'];
$skill = $data['skill'];
$skills = join(",",$skill);
$city = $data['cities'];
$query = $this->db->query("SELECT DISTINCT(U.user_id), U.firstname, U.lastname, U.username, U.usertype, U.email, U.phone, U.address, U.profile_image, C.name AS country,C.id AS countryid, S.name AS state,S.id AS stateid, A.housename, A.street, A.area, A.po, A.city, CJ.designation, CJ.resume, CJ.biography, CJ.hiring_mode, CJ.notice_period, CJ.current_CTC, CJ.expected_CTC, D.designation_id AS desig, D.designation AS desig_name
FROM users AS U
LEFT JOIN address AS A ON U.user_id=A.cand_id
LEFT JOIN cand_job_details AS CJ ON CJ.cand_id=U.user_id
LEFT JOIN designations AS D ON D.designation_id=CJ.designation
LEFT JOIN countries AS C ON C.id=A.country
LEFT JOIN states AS S ON S.id=A.state
LEFT JOIN user_skills AS US ON U.user_id=US.user_id
LEFT JOIN user_interested_cities AS UC ON U.user_id=UC.user_id
WHERE D.designation LIKE '$designation' && (CJ.hiring_mode='2' || CJ.hiring_mode='$mode') && CJ
.notice_period<='$notice_period' && UC.city='$city' && US.skill IN(".implode(",", $skills).")
");
return $query;
}
How to implement this on codeigniter?
Thanks in advance
You need try to add ' around each argument. After it should looks like IN ('PHP','AngularJS'), because it is a string value and datatype is varchar as well.
$skills = "'";
foreach($skill as $item) {
$skills .= $item."',";
}
$skills = trim($skills,",")
Codeigniter comes with a built in Querybuilder - i strongly suggest to use it, because it makes your life much easier, and protects you against SQL injections - which is clearly a problem in your case.
Try the following
function fetch_candidate($data)
{
$this->db
->select('SELECT DISTINCT(U.user_id), U.firstname, U.lastname, U.username, U.usertype, U.email, U.phone, U.address, U.profile_image, C.name AS country,C.id AS countryid, S.name AS state,S.id AS stateid, A.housename, A.street, A.area, A.po, A.city, CJ.designation, CJ.resume, CJ.biography, CJ.hiring_mode, CJ.notice_period, CJ.current_CTC, CJ.expected_CTC, D.designation_id AS desig, D.designation AS desig_name')
->from('users U')
->join('address A', 'U.user_id=A.cand_id', 'left')
->join('cand_job_details CJ', 'CJ.cand_id=U.user_id', 'left')
->join('designations D', 'D.designation_id=CJ.designation', 'left')
->join('countries C', 'C.id=A.country', 'left')
->join('states S', 'S.id=A.state', 'left')
->join('user_skills US', 'U.user_id=US.user_id', 'left')
->join('user_interested_cities UC', 'U.user_id=UC.user_id', 'left');
if (isset($data['designation']) && !empty($data['designation']))
{
$this->db->like('D.designation', $data['designation']);
}
if (isset($data['mode']) && !empty($data['mode']))
{
$this->db
->group_start()
->where('CJ.hiring_mode', 2)
->or_where('CJ.hiring_mode', $data['mode'])
->group_end();
}
if (isset($data['notice_period']) && !empty($data['notice_period']))
{
$this->db->where('CJ.notice_period <=', $data['notice_period']);
}
if (isset($data['city']) && !empty($data['city']))
{
$this->db->where('UC.city', $data['city']);
}
if (isset($data['skills']) && is_array($data['skills']))
{
$this->db->where_in('US.skill', $data['skills']);
}
return $this->db->get();
}

How to fix this query using Zend Framework2

I'm using ZendFramework2 and I need to make a custon query. I tried my query in mysql and it works perfectly.
SELECT p.idProyecto,p.nombre, e.nombre, e.apellido, sum(ar.tiempoEstimado)
estimado,DATE_FORMAT(p.fechaInicio, '%Y/%m/%d') as inicio,
DATE_FORMAT(p.fechaFin, '%Y/%m/%d') as fin, sum(r.tiempoRegistrado) as t_real
FROM Actividad as a
LEFT JOIN ActividadResponsable as ar
ON a.idActividad=ar.idActividad
and a.fechaInicio>="2014-10-13"
and a.fechaFin<="2014-10-19"
LEFT JOIN ActividadPlaneada as ap
On ap.idActividad = ar.idActividad
and ar.idActividad = a.idActividad
LEFT JOIN tipoActividad as ta
on ta.idTipoActividad= ap.idTipoActividad
LEFT JOIN proyecto as p
ON p.idProyecto=a.idProyecto
LEFT JOIN registro as r
ON a.idActividad=r.idActividad
and r.fechaRegistro>="2014-10-13 00:00:00"
and r.fechaRegistro<="2014-10-19 23:59:00"
LEFT JOIN empleado as e
ON p.creador = e.idEmpleado
GROUP BY a.idProyecto;
But when I code this into ZendFramework2 it changes this
LEFT JOIN ActividadResponsable as ar
ON a.idActividad=ar.idActividad
and a.fechaInicio>="2014-10-13"
and a.fechaFin<="2014-10-19"
So the result query that zend generates is
SELECT p.idProyecto, p.nombre, e.nombre, e.apellido, SUM(ar.tiempoEstimado) as estimado, p.fechaInicio as inicio, p.fechaFin as fin, sum(r.tiempoRegistrado) as t_real
FROM `Actividad`
LEFT JOIN `ActividadResponsable` AS `ar` ON `Actividad`.`idActividad`=`ar`.`idActividad`
LEFT JOIN `ActividadPlaneada` AS `ap` ON `ap`.`idActividad` = `ar`.`idActividad` and `ar`.`idActividad` = `Actividad`.`idActividad`
LEFT JOIN `TipoActividad` AS `ta` ON `ta`.`idTipoActividad`= `ap`.`idTipoActividad`
LEFT JOIN `Proyecto` AS `p` ON `p`.`idProyecto`=`Actividad`.`idProyecto`
LEFT JOIN `Registro` AS `r` ON `Actividad`.`idActividad`=`r`.`idActividad`
LEFT JOIN `Empleado` AS `e` ON `p`.`creador` = `e`.`idEmpleado`
WHERE `Actividad`.`fechaInicio` >= :where1 AND `Actividad`.`fechaFin` <= :where2 AND `r`.`fechaRegistro` >= :where3 AND `r`.`fechaRegistro` <= :where4
GROUP BY `Actividad`.`idProyecto`
The php code I have is this
$dbAdapterConfig = array(
'driver' => 'Pdo_Mysql',
'database' => '*',
'username' => '*',
'password' => '*',
'charset' => 'utf8'
);
$dbAdapter = new Adapter($dbAdapterConfig);
$sql = new Sql($dbAdapter);
$query = $sql->select();
$query->from('Actividad');
$query->columns(array(new \Zend\Db\Sql\Expression('p.idProyecto, p.nombre, e.nombre, e.apellido, SUM(ar.tiempoEstimado) as estimado, p.fechaInicio as inicio, p.fechaFin as fin, sum(r.tiempoRegistrado) as t_real')));
$query->join(array('ar' => 'ActividadResponsable'), 'Actividad.idActividad=ar.idActividad', array(), 'left');
$query->where->greaterThanOrEqualTo('Actividad.fechaInicio', $inicio);
$query->where->lessThanOrEqualTo('Actividad.fechaFin', $fin);
$query->join(array('ap' => 'ActividadPlaneada'), 'ap.idActividad = ar.idActividad and ar.idActividad = Actividad.idActividad', array(), 'left');
$query->join(array('ta' => 'TipoActividad'), 'ta.idTipoActividad= ap.idTipoActividad', array(), 'left');
$query->join(array('p' => 'Proyecto'), 'p.idProyecto=Actividad.idProyecto', array(), 'left');
$query->join(array('r' => 'Registro'), 'Actividad.idActividad=r.idActividad', array(), 'left');
$query->where->greaterThanOrEqualTo('r.fechaRegistro', "2014-10-13 00:00:00");
$query->where->lessThanOrEqualTo('r.fechaRegistro', "2014-10-19 23:59:00");
$query->join(array('e' => 'Empleado'), 'p.creador = e.idEmpleado', array(), 'left');
$query->group(array('Actividad.idProyecto'));
$statement = $sql->prepareStatementForSqlObject($query);
$result = $statement->execute();
$records = array();
foreach ($result as $return) {
$records[] = $return;
}
return $result;
the and's in the join query belongs to the joins on statement not the queries where statement , you need to add the on statement as a Expression like this :
$exp = new Expression('Actividad.idActividad=ar.idActividad and a.fechaInicio>=?
and a.fechaFin<=?',array($inicio,$fin));
$query->join(array('ar' => 'ActividadResponsable'), $exp , array(), 'left');

Converting MySQL query to CI syntax

I have a problem converting my MySQL query to codeigniter syntax.
This is my MySQL query.
Select id, name, code, status, question_count, session
from s3r_set
left join
(Select set_id, count(id) as question_count
from s3r_question group by set_id) question
on question.set_id = id
left join
(SELECT session_id as session, set_id
from s3r_session) s3rsession
on s3rsession.set_id = id
order by id
This is what I've got so far in CI:
$this->db->select('id, name, code, status, question_count, session');
$this->db->from('s3r_set');
$this->db->join('s3r_question', '(Select set_id, count(id) as question_count
from s3r_question group by set_id) question
on question.set_id = id', 'left');
$this->db->join('s3r_session', '(SELECT session_id as session, set_id
from s3r_session) s3rsession
on s3rsession.set_id = id', 'left');
$this->db->order_by('id', "desc");
$q = $this->db->get();
if($q->num_rows() > 0)
{
return $q->result();
}
else
{
return false;
}
Thanks for help in advance.
Well for one you are doing the join wrong:
$this->db->join('s3r_question', '(Select set_id, count(id) as question_count
from s3r_question group by set_id) question
on question.set_id = id', 'left');
Should be:
$this->db->join('(Select set_id, count(id) as question_count
from s3r_question group by set_id) question', 'question.set_id = id');
Refer to formatting here:
http://ellislab.com/codeigniter/user-guide/database/active_record.html#join
The ...join(FROM_TABLE, ON WHAT VALUE TO JOIN ON, OPTIONAL > WHAT TYPE OF JOIN, LEFT/RIGHT/ETC;)

How to join the same table twice and assign table aliases in Codeigniter?

I'm trying to make a mail system in Codeigniter with the PyroCms.
In my mail table, I have a "recipent" row and a "sender" row which contains the user id of the sender and recipient. To retrieve usernames from the ids, I'm trying to join the table together, but it simply returns me this error:
Error Number: 1066
Not unique table/alias: 'default_users'
SELECT `default_mailsystem`.*, `default_users`.`username` AS modtager, `default_users`.`username` as afsender
FROM (`default_mailsystem`)
LEFT JOIN `default_users` ON `default_mailsystem`.`recipent` = `default_modtager`.`id`
LEFT JOIN `default_users` ON `default_mailsystem`.`sender` = `default_afsender`.`id`
ORDER BY `id` DESC
Filename: /hsphere/local/home/brightmedia/reuseable.dk/modules/mail/models/mail_m.php
Line Number: 13
My code is as follows:
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
->join('users', 'mailsystem.recipent = modtager.id', 'left')
->join('users', 'mailsystem.sender = afsender.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
The funny thing is, that if I remove the last "join" operation and leave it to only join the recipient of the mail it all works out well.
This is very simple
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND mailsystem.sender = afsender.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
Have you tried forcing an alias in the join function (the "AS" operator won't work in the select clause as you have it...)?
<?php
$this->db->select('mailsystem.*, modtager.username AS modtager_name, afsender.username as afsender_name')
->join('`users` `modtager`', 'mailsystem.recipent = modtager.id', 'left')
->join('`users` `afsender`', 'mailsystem.sender = afsender.id', 'left');
$this->db->order_by('mailsystem.id', 'DESC');
return $this->db->get('mailsystem')->result();
Use alias like this -
$this->db->select('mailsystem.*, users_table_a.username AS modtager, users_table_b.username as afsender')
$this->db->join('users users_table_a', 'mailsystem.recipent = users_table_a.id', 'left');
$this->db->join('users users_table_b', 'mailsystem.sender = users_table_b.id', 'left');
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
you can use this :
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND mailsystem.sender = afsender.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
*If you are using any db prefix use this *
$this->db->select('mailsystem.*, users.username AS modtager, users.username as afsender')
$this->db->join('users', 'mailsystem.recipent = modtager.id AND '.$this->db->dbprefix('mailsystem').'.sender = '.$this->db->dbprefix('afsender').'.id', 'left')
$this->db->order_by('id', 'DESC');
return $this->db->get('mailsystem')->result();
Its very easy to get data from single table
$this->db->select('a.*,b.fname AS cname,c.fname as uname');
$this->db->from('tbl_menus a');
$this->db->join('tbl_admin_login b', 'b.id = a.create_by', 'left');
$this->db->join('tbl_admin_login c', 'c.id = a.update_by', 'left');
$this->db->order_by('a.id', 'desc');
return $this->db->get()->result_array();
At the time of this thread, i figured that the codeigniter call missed out the possibility to do AS inside of a join, Therefor this solved the issue:
$sql = "
SELECT default_mailsystem.*,
recipent.first_name AS modtager,
sender.first_name AS afsender
FROM default_mailsystem
LEFT JOIN default_profiles AS recipent ON recipent.id = default_mailsystem.id
LEFT JOIN default_profiles AS sender ON sender.id = default_mailsystem.id
";
return $this->db->query($sql)->result();
Your can try this
Core PHP
SELECT `custome_module`.`id`, `custome_module`.`name`, min(l1.nmark_completed) as call_waiter, min(l2.nmark_completed) as bill, min(l3.nmark_completed) as tray, min(l4.nmark_completed) as ordera
FROM `custome_module`
LEFT JOIN `restaurant_logs` as `l1` ON `custome_module`.`id` = `l1`.`nmodule_id` AND `l1`.`ntype` = 1
LEFT JOIN `restaurant_logs` as `l2` ON `custome_module`.`id` = `l2`.`nmodule_id` AND `l2`.`ntype` = 2
LEFT JOIN `restaurant_logs` as `l3` ON `custome_module`.`id` = `l3`.`nmodule_id` AND `l3`.`ntype` = 6
LEFT JOIN `restaurant_logs` as `l4` ON `custome_module`.`id` = `l4`.`nmodule_id` AND `l4`.`ntype` = 5
WHERE `custome_module`.`nbranch_id` = '142'
GROUP BY `custome_module`.`id`
and also in Codeigniter
$this->db->select('custome_module.id, custome_module.name, min(l1.nmark_completed) as call_waiter, min(l2.nmark_completed) as bill,min(l3.nmark_completed) as tray,min(l4.nmark_completed) as ordera');
$this->db->from("custome_module");
$this->db->join('restaurant_logs as l1', 'custome_module.id = l1.nmodule_id AND l1.ntype = 1', 'left');
$this->db->join('restaurant_logs as l2', 'custome_module.id = l2.nmodule_id AND l2.ntype = 2', 'left');
$this->db->join('restaurant_logs as l3', 'custome_module.id = l3.nmodule_id AND l3.ntype = 6', 'left');
$this->db->join('restaurant_logs as l4', 'custome_module.id = l4.nmodule_id AND l4.ntype = 5', 'left');
$this->db->where('custome_module.nbranch_id', $this->data['user_session']['nid']);
$this->db->get();

Categories