Converting MySQL query to CI syntax - php

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;)

Related

codeigniter, join table properties overrides other properties

I'm working on a project using codeigniter 3 and I have a following query
$this->db->select("*");
$this->db->from("questions");
$this->db->join('users', 'users.id = questions.user_id');
$this->db->where('article_id', $articleId);
$this->db->order_by('questions.id', 'DESC');
$query = $this->db->get();
return $query->result();
// query
// SELECT * FROM `questions` JOIN `users` ON `users`.`id` = `questions`.`user_id` WHERE `article_id` = 18 ORDER BY `questions`.`id` DESC
Currently, the id property from users table overrides the questions id one. The question's id is crucial.
I worry, I will have to write a custom query, which I am not really good at.
Try to do this as follow:
$this->db->select("*, questions.id as question_id");
It's obvious that properties with the same name will be overriden. That's why you should assign to them 'unique' names in select statement.
You can specifically mention the ids with alies like -
$this->db->select("questions.id as question_id, users.id as user_id, questions.*, users.*");
$this->db->from("questions");
$this->db->join('users', 'users.id = questions.user_id');
$this->db->where('article_id', $articleId);
$this->db->order_by('questions.id', 'DESC');
$query = $this->db->get();
return $query->result();
This will give you specific columns named with question_id, user_id, questions table's all columns, users table's all columns
Or another better solution to use specific column names in select with alies if required.

codeigniter join from 2nd table id with 3rd table id multi rows

I want to join multiple tables, as in my picture:
Here is my code:
$this->db->select('
pt2.turl as `p_img`,
p.title as `p_title`,
p.text as `p_text`,
p.create as `p_date`,
pt3.turl as `c_img`,
u.name as `c_name`,
c.text as `c_text`,
c.create as `c_date`
');
$this->db->from('posts as p, users as u, photos as pt2, photos as pt3');
$this->db->join('comments as c', 'p.id=c.pid AND u.id=c.uid');
$this->db->join('posts as p2', 'p2.pid=pt2.id', 'rihgt');
$this->db->join('users as u2', 'u2.photoid=pt3.id', 'right');
$this->db->order_by('c.id', 'DESC');
$this->db->limit('7');
$qry = $this->db->get();
return $qry->result();
If I understand you correctly, this is kind of what you're looking for. I haven't tried it out so it may not be exact, but you shouldn't need to make 2 table associations (pt2 and pt3) for the same table in the join. Just Include them in the select and join on the unique ID's
The "Left" is a join that is centered around you're left table so everything hangs off of that. Since you are joining the users table before the photo table, you should be able to join on its columns.
Hope this helps. Let me know if I missed something. :)
$select = array(
pt2.turl as `p_img`,
p.title as `p_title`,
p.text as `p_text`,
p.create as `p_date`,
pt2.turl as `c_img`,
u.name as `c_name`,
c.text as `c_text`,
c.create as `c_date`
);
//Set tables to variables. Just makes it easier for me
$postsTable = "posts as p"; //This will be your left table.
$userTable = "Users as u";
$commentsTable = "comments as c";
$photosTable = "photos as pt2";
$this
->db
->select($select)
->from($postsTable)
->join($userTable, "p.uid = u.id", "left")
->join($commentsTable, "p.cid = c.id", "left")
->join($photosTable, "u.photoid = pt2.id", "left")
->get();
I solved this problem myself
It would be like this:
$select= array (
//'*',
'pt.turl p_img',
'p.title p_title',
'p.text p_text',
'p.create p_date',
'pt2.turl c_img',
'c.text c_text',
'u.name c_name',
'c.create c_date'
);
$from = array (
'posts p'
);
$qry = $this
->db
->select($select)
->from($from)
->join('comments c', 'c.pid=p.id')
->join('photos pt', 'pt.id=p.pid')
->join('users u', 'u.id=c.uid')
->join('photos pt2', 'u.photoid=pt2.id')
->order_by('c.create', 'DESC')
->limit('7')
->get();
return $qry->result();

Group By Three columns doesn't work in CodeIgniter

I needed a result with Group By three columns and the SQL works perfectly without any issue. I'm facing the issue when I use it in the CodeIgniter framework; it doesn't execute the query. My Code and SQL are as follows.
Code
$this->db->select(['trk.userid AS user_id', 'scr.course AS course_id'])
->from('mdl_scorm scr')
->join('mdl_scorm_scoes_track trk', 'scr.id = trk.scormid', 'inner')
->join('mdl_course_modules mcs', 'mcs.instance = scr.id', 'inner')
->where_in('trk.value', ['completed','incomplete','passed'])
->group_by(['scr.course', 'trk.userid', 'trk.scormid'])
->order_by('trk.userid', 'DESC');
SQL
SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM (`mdl_scorm` scr)
INNER JOIN `mdl_scorm_scoes_track` trk ON `scr`.`id` = `trk`.`scormid` INNER JOIN `mdl_course_modules` mcs ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid` DESC LIMIT 0,100;
This works fine when the group_by has only two columns, like,
->group_by(['scr.course', 'trk.userid'])
What could be the reason?
In codeigniter group_by() works with two fields only.
$this->db->group_by()
Permits you to write the GROUP BY portion of your query:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
CI 3 group_by()
Edit 01
$query=$this->db->query("
SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM `mdl_scorm` scr
INNER JOIN `mdl_scorm_scoes_track` trk
ON `scr`.`id` = `trk`.`scormid`
INNER JOIN `mdl_course_modules` mcs
ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid`
DESC LIMIT 0,100;");
$result = $query->result_array();
return $result;
Consider a raw query in the model.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class xyz_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_this_thing($month,$year)
{ $myQuery="SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM `mdl_scorm` scr
INNER JOIN `mdl_scorm_scoes_track` trk
ON `scr`.`id` = `trk`.`scormid`
INNER JOIN `mdl_course_modules` mcs
ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid`
DESC LIMIT 0,100;";
$query = $this->db->query($myQuery);
$result = $query->result();
return $result;
}
}
You can also pass an array of multiple values as well:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
Source link
use result array instead of the result like
return $query->result_array();

selecting a colum from joined tabels in database Codeigniter

I am trying to select column name level_name from table levels,
which contains level_id and level_name,
for a user to know what is their level,
The table of users named as users and contain a level_id and user_id,
but I get this error ->
Column 'level_id' in on clause is ambiguous
SELECT `level_name`
FROM `levels`
JOIN `users` ON `level_id` = `level_id` WHERE `user_id` = '9'
here it is the code in the model
public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels');
$this->db->join('users', 'level_id = level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query;
}
thanks in advance :)
Change the query to
SELECT `level_name`
FROM `levels` l
JOIN `users` u ON `u`.`level_id` = `l`.`level_id`
WHERE `user_id` = '9'
if you like the table name aliasing method, it is shorter and easier to read.
Or
SELECT `level_name`
FROM `levels`
JOIN `users` ON `users`.`level_id` = `levels`.`level_id`
WHERE `user_id` = '9'
If you prefere to use the full table name everywhere.
Because both tables contain a column with the name level_id the query analyser need to know which one you are addressing.
In codeigniter try
public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels l');
$this->db->join('users u', 'u.level_id = l.level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query;
}
Select l.level_name
FROM levels l
JOIN users u
ON u.level_id = l.level_id
and u.user_id = '9'
public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels');
$this->db->join('users', 'levels.level_id = users.level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query;
}
public function level_ownprofile($user_id)
{
$this->db->select('l.level_name');
$this->db->from('levels as l');
$this->db->join('users as u', 'l.level_id = u.level_id');
$this->db->where('l.user_id', $user_id);
$query = $this->db->get();
return $query->results();
}

Sql Combining AND with OR in codeigniter

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 ;

Categories