Using Having(count()) with CIs active record - php

I have the following SQL query but I can't seem to find out how I would change this query to make it work with CI:
SELECT *
FROM Table1
JOIN Table2 ON Table2.tID = Table1.tID
JOIN Table3 ON Table3.vID = Table2.vID
WHERE vegetable
IN (
'Potatoe', 'Carrot'
)
GROUP BY Table1.tID
HAVING COUNT( DISTINCT vegetable ) =2
Here is what I have so far on CI:
$arrCount = count($array);
$this->db->select('*');
this->db->from('Table1');
$this->db->join('Table2', 'Table2.tID = Table1.tID');
$this->db->join('Table3', 'Table3.vID = Table2.vID');
$this->db->where_in('vegetable', $array);
$this->db->group_by("Table1.tID");
$this->db->having('vegetable');
$this->db->count_all($arrCount);
$q = $this->db->get();
But doing this gives me the following sql statement:
Table 'DatabaseTest.2' doesn't exist
SELECT COUNT(*) AS `numrows` FROM `2`
I am pretty sure the ActiveRecord count I have used is incorrect but I am not sure what else it would be because I have found any COUNT() function with CI.
So my question is how can I make my SQL query in CodeIgniter?
Extra note, I have also tried running the query using CIs $this->db->query but get an array error, when looking with the in.
$this->db->query('SELECT *
FROM Table1
JOIN Table2 ON Table2.tID = Table1.tID
JOIN Table3 ON Table3.vID = Table2.vID
WHERE vegetables
IN (
' .$array . '
)
GROUP BY Table1.tID
HAVING COUNT( DISTINCT vegetables ) =' . $arrCount);
And heres the error message:
Unknown column 'Array' in 'where clause'
So it is assuming that I am using a where instead of a where in it looks like. Again can someone help me get my sql to work with CIs active record?

I haven't tested the first query with active records, but wouldn't this work? count_all is a query of on it's own. The first parameter is suppose to be the table... you entered the size of your array as the table which is 2!!! active records reference
$arrCount = sizeof($array);
$this->db->select('*');
this->db->from('Table1');
$this->db->join('Table2', 'Table2.tID = Table1.tID');
$this->db->join('Table3', 'Table3.vID = Table2.vID');
$this->db->where_in('vegetable', $array);
$this->db->group_by("Table1.tID");
$this->db->having('COUNT(DISTINCT vegetable)', $arrCount);
$q = $this->db->get();
Also, for the query, you need to convert your array into a string:
$this->db->query('SELECT *
FROM Table1
JOIN Table2 ON Table2.tID = Table1.tID
JOIN Table3 ON Table3.vID = Table2.vID
WHERE vegetables
IN (
' .implode(',',$array) . '
)
GROUP BY Table1.tID
HAVING COUNT( DISTINCT vegetables ) =' . $arrCount);

$this->db->query('SELECT *
FROM Table1
JOIN Table2 ON Table2.tID = Table1.tID
JOIN Table3 ON Table3.vID = Table2.vID
WHERE vegetables
IN ("' . implode('", "', $array) . '")'
GROUP BY Table1.tID
HAVING COUNT( DISTINCT vegetables ) =' . $arrCount);
Use implode() to turn your array into a MySQL readable string.
EDIT: Implode with quotes.

I might suggest get $this->db->count_all($arrCount); line away, at less until you get this working.

Related

MySQL error #1054 unknown column in field

This is my query:
SELECT COUNT( DISTINCT (paypal_transaction.buyerId) ) AS cid FROM eg_posts_details
INNER JOIN paypal_transaction ON paypal_transaction.id = eg_posts_details.OrderId
WHERE seller_id =190
It runs perfectly on MySQL directly but when I run it from my PHP codeigniter model I get the #1054 error. I have no idea why this is happening. Please help.
Here is the PHP code:
$query = $this->db->query("SELECT COUNT( DISTINCT (paypal_transaction.buyerId) ) AS cid
FROM eg_posts_details
INNER JOIN paypal_transaction ON paypal_transaction.id = eg_posts_details.OrderId
WHERE seller_id =190");
As per your image reference, paypal transaction table contain buyerId and you used it as buyer_id. So use the following.
Use like this
$sql = "select count(distinct(`paypal_transaction`.`buyerId`)) as `cid` from `eg_posts_details` inner join `paypal_transaction` on `paypal_transaction`.`id` = `eg_posts_details`.`OrderId` where `seller_id`= '190' ";
$query = $this->db->query($sql);
Hope its work for you

How do I nest joins inside a from statement in Codeigniter

Okay, I've been tasked with rewriting a small, old PHP app in Codeigniter, and I ran into a bit a road bump. I'm not sure how to go about handling the joins in the query.
FROM(
(
(
(
(mobiledoc.labdata labdata JOIN mobiledoc.items items
ON (labdata.ItemId = items.itemID)
) JOIN mobiledoc.enc enc
ON (labdata.EncounterId = enc.encounterID)
) JOIN mobiledoc.users users_patient
ON (users_patient.uid = enc.patientID)
) JOIN mobiledoc.users users_Provider
ON (users_Provider.uid = enc.doctorID)
) JOIN mobiledoc.facilitygroupmembers facilitygroupmembers
ON (enc.facilityId = facilitygroupmembers.FacilityId)
)
And then after that FROM there are a few more joins, which I think would be fairly easy.
JOIN mobiledoc.facilitygroups facilitygroups ON (facilitygroups.Id = acilitygroupmembers.GroupId)
JOIN mobiledoc.patients patients ON (enc.patientID = patients.pid)
Any help would be greatly appreciated.
UPDATE:
I decided to just put the nested joins inside the for statement, and move on. Here's the original query.
$result = mysql_query("SELECT patients.ControlNO AS PatientID, users_patient.ulname AS patulname,
users_patient.ufname AS patufname, users_patient.uminitial AS patuminitial, users_patient.dob AS
patdob, users_Provider.ulname AS ULname, users_Provider.ufname AS UFname, items.itemName,
labdata.Notes,enc.date, enc.startTime FROM(((((mobiledoc.labdata labdata JOIN mobiledoc.items
items ON (labdata.ItemId = items.itemID)) JOIN mobiledoc.enc enc ON (labdata.EncounterId =
enc.encounterID)) JOIN mobiledoc.users users_patient ON (users_patient.uid = enc.patientID)) JOIN
mobiledoc.users users_Provider ON (users_Provider.uid = enc.doctorID)) JOIN
mobiledoc.facilitygroupmembers facilitygroupmembers ON (enc.facilityId =
facilitygroupmembers.FacilityId)) JOIN mobiledoc.facilitygroups facilitygroups ON
(facilitygroups.Id = facilitygroupmembers.GroupId) JOIN mobiledoc.patients patients ON
(enc.patientID = patients.pid) WHERE (facilitygroups.Name = '". $_POST['facility_id'] . "') AND
(items.itemName LIKE '%X RAY%' OR items.itemName LIKE '%Cast%' OR items.itemName LIKE '%Splint%'
OR items.itemName LIKE '%DEXA%') AND (enc.VisitType NOT IN ('', 'MT', 'TEL')) AND (enc.`date` =
'" . $_POST['txtYear'] . "-" . $_POST['txtMonth'] . "-" . $_POST['txtDay'] ."') ORDER BY
enc.startTime ASC") or die ("could not execute query!");
Here's the new query:
$this->db->select('patients.ControlNO as id');
$this->db->select('users_patient.ulname as lastName');
$this->db->select('users_patient.ufname as firstName');
$this->db->select('users_patient.uminitial as mInitial');
$this->db->select('users_patient.dob as dob');
$this->db->select('users_Provider.ulname as phys_lastName');
$this->db->select('items.itemName');
$this->db->select('labdata.notes');
$this->db->select('enc.date');
$this->db->select('enc.startTime');
$this->db->from('((((mobiledoc.labdata labdata JOIN mobiledoc.items items ON (labdata.ItemId
= items.itemID)) JOIN mobiledoc.enc enc ON (labdata.EncounterId = enc.encounterID)) JOIN
mobiledoc.users users_patient ON (users_patient.uid = enc.patientID)) JOIN mobiledoc.users
users_Provider ON (users_Provider.uid = enc.doctorID)) JOIN mobiledoc.facilitygroupmembers
facilitygroupmembers ON (enc.facilityId = facilitygroupmembers.FacilityId)) JOIN
mobiledoc.facilitygroups facilitygroups ON (facilitygroups.Id = facilitygroupmembers.GroupId)
JOIN mobiledoc.patients patients ON (enc.patientID = patients.pid)');
$this->db->where($where_array);
$this->db->like($like_array);
$this->db->or_like($or_like_array);
$this->db->where_not_in('enc.VisitType', $not_in);
$this->db->order_by('enc.startTime', 'asc');
$this->db->get();
And the output from that query:
SELECT `patients`.`ControlNO` as id, `users_patient`.`ulname` as lastName,
`users_patient`.`ufname` as firstName, `users_patient`.`uminitial` as mInitial,
`users_patient`.`dob` as dob, `users_Provider`.`ulname` as phys_lastName, `items`.`itemName`,
`labdata`.`notes`, `enc`.`date`, `enc`.`startTime` FROM ((((((mobiledoc.labdata labdata JOIN
mobiledoc.items items ON (labdata.ItemId = items.itemID)) JOIN mobiledoc.enc enc ON
(labdata.EncounterId = enc.encounterID)) JOIN mobiledoc.users users_patient ON (users_patient.uid
= enc.patientID)) JOIN mobiledoc.users users_Provider ON (users_Provider.uid = enc.doctorID))
JOIN mobiledoc.facilitygroupmembers facilitygroupmembers ON (enc.facilityId =
facilitygroupmembers.FacilityId)) JOIN mobiledoc.facilitygroups facilitygroups ON
(facilitygroups.Id = facilitygroupmembers.GroupId) JOIN mobiledoc.patients patients ON
(enc.patientID = patients.pid)) WHERE `facilitygroups`.`Name` = 0 AND `enc`.`date` = '12/05/2014'
AND `enc`.`VisitType` NOT IN ('', 'MT', 'TEL') AND `items`.`itemName` LIKE '%X RAY%' OR
`items`.`itemName` LIKE '%DEXA%' OR `0` LIKE '%items.itemName%' ORDER BY `enc`.`startTime` asc
With CI's active record you can easily join tables by using the following format
$qry = $this->db->select('*')
->from('table1')
->where('table1.id', 1)
->join('table2','table2.t_id = table1.id')
->get();
For more information take a look at CI's active record documentation
Also you can specify the join type by adding a third parameter to the join() function
$this->db->join('table3', 'table3.id = table2.t_id', 'left');

Convert this MySQL Query to Codeigniter Active Record

I have got two tables :
Dress (dress_id, title)
Dress_comment (comment_id, dress_id, comment)
I have been trying from hours now and unable to convert this query into the corresponding Codeigniters' Active Class Record functions.
Here is the query :
SELECT d.dress_id, d.title, COALESCE(dc.count, 0)
FROM dress d
JOIN (select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc
ON d.dress_id = dc.dress_id
ORDER BY d.dress_id;
This is what I have tried till now :
//Creating the select subquery for the inner join
$this->db->select('dress_id, count(comment_id) as count')
->from('Dress_comment')
->group_by('dress_id')
->get();
$subQuery = $this->db->last_query();
//Main Query
$this->db->select('d.dress_id, d.title, COALESCE(dc.count,0)')
->from('Dress')
->join($subQuery . ' dc','dc.dress_id = d.dress_id','left')
->order_by('d.dress_id');
$result = $this->db->get();
return $result->result_array();
But Codeigniter is not running this query and always giving mysql syntax error. The sql format that codeigniter is converting this active methods to is
SELECT `d`.`dress_id`, `d`.`title`, COALESCE(dc.count, `0)`
FROM (`Dress`) LEFT JOIN `SELECT` `dress_id`, count(comment_id) as count
FROM (`Dress_comment`)
GROUP BY `dress_id` dc
ON `dc`.`dress_id` = `d`.`dress_id`
ORDER BY `d`.`dress_id`
I was able to solve the problem using the mysql query in the join function like this :
$this->db->select('d.dress_id, d.title, dc.count as comments, dl.count as likes, dt.title, di.image_url')
->from('Dress d')
->join('(select dress_id, count(comment_id) as count from dress_comment group by dress_id) dc','dc.dress_id = d.dress_id','left')
->order_by('d.dress_id');

Codeigniter not showing proper results for array fetched by MySQL query.

I am working with Codeigniter with mysql databases,
I have a model function
public function get_all_data(){
$this->output->enable_profiler(TRUE);
$years = $this->input->post('year');
$months = $this->input->post('month');
$exec_ids = $this->input->post('exec_id');
$query = $this->db->query("SELECT * FROM client_booking AS cb
RIGHT OUTER JOIN executive_client_unit_relation AS ecur ON cb.id = ecur.booking_id
LEFT OUTER JOIN new_invoice ON cb.id = new_invoice.booking_id
WHERE ecur.executive_id IN (" . implode(',', $exec_ids) . ") AND MONTH(cb.booking_date) IN (" . implode(',', $months) . ") AND YEAR(cb.booking_date) IN (" . implode(',', $years) . ")");
return $query->result();
}
The sql generated by this is (as seen in the profiler) :
SELECT * FROM client_booking AS cb
RIGHT OUTER JOIN executive_client_unit_relation AS ecur ON cb.id = ecur.booking_id
LEFT OUTER JOIN new_invoice ON cb.id = new_invoice.booking_id
WHERE ecur.executive_id IN (4,5,6) AND MONTH(cb.booking_date) IN (1,2,3,4,5) AND YEAR(cb.booking_date) IN (2013,2014)
My problem is that the booking_id value is set to NULL when I var_dump() the result of this query.
On the other hand, when I run the SQL in my phpmyadmin, everything goes well and I can see the booking_id
PS: client_booking table's primary key is id which is the booking_id for all the other tables.
Can anyone help me to resolve this?
You are using LEFT/RIGHT joins so when there is no association found between your tables a null row will be returned ,second thing is your tables new_invoice and executive_client_unit_relation both have common names for the column name booking_id and in your select statement you are doing select * so for the columns with same name i guess the last one is picked which is null,for the solution you either you select only needed columns not all like SELECT cb.* or either the columns have same name with your query table then specify them individually with the alias you wish to provide but in the end of select statement in query like SELECT *,cb.id AS booking_id,....

Not a unique table/alias stock:

Ive got the query below :
$sql = "SELECT `scanners`.`KordNo`, `scanners`.`BundleNumber`
FROM `scanners`, `TWOrder`, `Stock`
INNER JOIN `TWORDER` ON `scanners`.`KordNo` = `TWOrder`.`KOrdNo`
AND `scanners`.`Date` = '" . $date . "'
INNER JOIN `Stock` ON `TWOrder`.`Product` =`Stock`.`ProductCode`
AND `Stock`.`ProductGroup` NOT BETWEEN 400 AND 650
AND `scanners`.`Scanner` IN (
ORDER BY `scanners`.`KordNo` ASC";
foreach($scanner as $x)
{$sql .= $x . ",";}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
$return[] = $row;
}
When i echo the sql on php my admin i get the error not a unique table/alias stock;
can someone advise?
Since you're using explicit JOINs, drop the other two tables off of the FROM clause.
...
FROM `scanners`
INNER JOIN `TWORDER` ON `scanners`.`KordNo` = `TWOrder`.`KOrdNo`
...
On line 2 you have...
FROM `scanners`, `TWOrder`, `Stock`
Then you have some INNER JOINs on to TWOrder and Stock.
That's mixing syntax (, and JOIN) which is messy. Stick to JOIN
It means that TWOrder and Stock are mentioned Twice in the query
If you REALLY need to include those table multiple times in one query, you need to give them alias names, so they can be distiguished from each other.
But I think it's probably a mistake and that Line 2 should just be
FROM `scanners`
Then, also, I'm not sure how you got that to compile. You have IN ( and then an ORDER BY clause, to which you append a list of values. You should append the list before the ORDER BY and then append the ORDER BY after you've finished the loop.

Categories