Mysql query convert into codeigniter active record - php

I have this query to convert into the Active record
SELECT (SELECT image FROM bc_item_image WHERE item_id = i.id LIMIT 1) as item_image, i.description, i.condition,c.cat_name as category_name,i.id as ID FROM bc_item i,bc_category c WHERE i.cat_id = c.id and i.user_id !='$user_id' and i.status = '1' and i.is_bartered = '0' and i.is_cancel = '0' and FIND_IN_SET('$subcat_id',i.interested_cat) order by i.display_count desc

use
$this->db->query('here your SQL query');

$this->db->select(" i.description, i.condition,c.cat_name as category_name,i.id,(SELECT image FROM bc_item_image WHERE item_id = i.id LIMIT 1) as item_image");
$this->db->from('bc_item as i');
$this->db->join('bc_category as c', 'i.cat_id = c.id');
$this->db->where('i.status', 1);
$this->db->where('i.is_bartered', 0);
$this->db->where('i.user_id','!=', $user_id);
$this->db->where('i.is_cancel', 0);
$this->db->where("FIND_IN_SET('".$subcat_id."','i.interested_cat')");
$query = $this->db->get();

Related

How can i join table with second table latest record

i have two table like registration table and academicdetails table and i have two records in academic table according to registration id but i want to join with latest record of academic table.
Query:
SELECT a.*, b.status AS ac_status
FROM registration AS a
LEFT JOIN academicdetails AS b ON a.id = b.registration_id
WHERE b.status = '1'
ORDER BY id DESC
LIMIT 100
PHP code:
if(isset($search['category']) && $search['category']!=''){
$condition = ', TIMESTAMPDIFF(YEAR, a.dob, CURDATE()) AS age';
}
$this->db->select('a.*,b.status as ac_status'.$condition);
$this->db->from("registration as a");
$this->db->join('academicdetails as b','a.id = b.registration_id','left');
if(isset($search['search_by_name']) && $search['search_by_name']!=''){
$this->db->where('a.name', $search['search_by_name']);
}
if(isset($search['gender']) && $search['gender']!=''){
$this->db->where('a.gender', $search['gender']);
}
if(isset($search['status']) && $search['status']!=''){
$this->db->where('b.status', $search['status']);
}
if(isset($search['category']) && $search['category']!=''){
if($search['category']=='Youth'){
$this->db->where('age>10 AND age<18');
}elseif($search['category']=='Junior'){
$this->db->where('age>17 AND age<22');
}elseif($search['category']=='Senior'){
$this->db->where('age > 21');
}
}
if(isset($search['course']) && $search['course']!=''){
$this->db->where('b.course', $search['course']);
}
$this->db->limit($search['limit'], $search['start']);
$this->db->order_by($this->id, $this->order);
$this->db->group_by('a.id');
$query = $this->db->get();
Please try following query:
SELECT * FROM `registration` LEFT JOIN academicdetails on registration.id = academicdetails.id ORDER BY academicdetails.id desc LIMIT 100;
Try this:-
$this->db->select("a.*, b.status AS ac_status");
$this->db->from('registration AS a');
$this->db->join('academicdetails AS b', 'b.registration_id = a.id', 'left');
$this->db->where("b.status",1);
$this->db->order_by("b.id","DESC");//primary key or id of your academic table.
$this->db->limit(100);
$this->db->get();

How to use Join in Codeigniter for update Query

I have given my Codeigniter code below, here i need to update a record using join conditions. I used the below code, But shows error
$condition="a.assignto='0' and a.recstatus='1' and b.location='$location' and '$category' IN(SELECT categoryid FROM `tq_productcategory` where productid=c.productid and recstatus='1')";
$this->db->set($data);
$this->db->where($condition);
$this->db->limit($limit);
$this->db->join('tq_customer b','a.customerid=b.customerid');
$this->db->join('tq_product c','a.productid=c.productid');
$this->db->order_by("a.created_on", "asc");
$this->db->update('tq_customerservicesupport a');
Below is my error Msg
Unknown column 'b.location' in 'where clause'
UPDATE `tq_customerservicesupport` `a` SET `assignto` = '10' WHERE `a`.`assignto` = '0' and `a`.`recstatus` = '1' and `b`.`location` = '3227' and '1' IN(SELECT categoryid FROM `tq_productcategory` where productid = `c`.`productid` and `recstatus` = '1') ORDER BY `a`.`created_on` ASC LIMIT 1
Filename: D:/wamp/www/tooquik/system/database/DB_driver.php
Try this:
$sql = "UPDATE tq_customerservicesupport AS a JOIN tq_customer AS b ON a.customerid = b.customerid JOIN tq_product AS c ON a.productid = c.productid SET $data WHERE $condition ORDER BY a.created_on ASC LIMIT $limit";
$this->db->query($sql);
Make sure that the query is correct cause i just wrote it based on your data and better to check it in phpmyadmin to make sure it works fine with no errors.

Codeigniter 2 multiple join and where statement

Updated code
$office = $this->session->userdata('department');
$query = "SELECT `doc`.`id`, `doc`.`barcode`, `doc`.`sub`, `doc`.`source_type`, `doc`.`sender`, `doc`.`address`, `doc`.`description`, `doc`.`receipient`, `doc`.`status`, DATE_FORMAT(`doc`.`datetime_added`, '%m/%d/%Y-%h:%i %p') as datetime_added,
(SELECT GROUP_CONCAT(`tag`) FROM `tags` WHERE `tags`.`documentId` = `doc`.`id` GROUP BY `tags`.`documentId`) as `tags`
FROM `documents` AS `doc`
JOIN `transactions` AS `trans` ON `doc`.`id` = `trans`.`document_id`
JOIN `trackers` AS `track` ON `doc`.`id` = `track`.`document_id`
WHERE `doc`.`status` = 'Processing'
AND `track`.`action` = '1')
AND `track`.`location` = '$office'
ORDER BY `doc`.`id` DESC";
$go = $this->db->query($query)->result_array();
var_dump($go); exit();
What I'm try to accomplish, is to display all documents located in our office that are Processing and has action 1. Documents may have tags like memo, request, finance, etc. The output is incorrect and not showing all the records that is in our office. I think there is a problem in WHERE clause? What could be the culprit in my code?
Update your query by removing the single quotes surrounding 1:
$query = "SELECT `doc`.`id`, `doc`.`barcode`, `doc`.`sub`, `doc`.`source_type`, `doc`.`sender`, `doc`.`address`, `doc`.`description`, `doc`.`receipient`, `doc`.`status`, DATE_FORMAT(`doc`.`datetime_added`, '%m/%d/%Y-%h:%i %p') as datetime_added,
(SELECT GROUP_CONCAT(`tag`) FROM `tags` WHERE `tags`.`documentId` = `doc`.`id` GROUP BY `tags`.`documentId`) as `tags`
FROM `documents` AS `doc`
JOIN `transactions` AS `trans` ON `doc`.`id` = `trans`.`document_id`
JOIN `trackers` AS `track` ON `doc`.`id` = `track`.`document_id`
WHERE `doc`.`status` = 'Processing'
**AND `track`.`action` = 1)**
AND `track`.`location` = '$office'
ORDER BY `doc`.`id` DESC";
$this->db->select("doc.id, doc.barcode, doc.sub, doc.source_type, doc.sender, doc.address, doc.description, doc.receipient, doc.status, DATE_FORMAT(doc.datetime_added, %m/%d/%Y-%h:%i %p) as datetime_added,
(SELECT GROUP_CONCAT(tag) FROM tags WHERE tags.documentId = doc.id GROUP BY tags.documentId) as tags")
->from("documents AS doc")
->join("transactions AS trans",'doc.id=trans.document_id')
->join("trackers AS track",'doc.id=track.document_id')
->where("doc.status","Processing")
->andWhere("track.action","1")
->andWhere("doc.id",$office)
->order_by("doc.id", "DESC");

How to convert normal sql query to Zend_Db_Select?

Hi I want to convert my normal mysql query to zend.db.select;
I want to use this script:
$select = $db->select();
// Add a FROM clause
$select->from( ...specify table and columns... )
// Add a WHERE clause
$select->where( ...specify search criteria... )
// Add an ORDER BY clause
$select->order( ...specify sorting criteria... );
$select->limit(20, 10);
for my query below
SELECT
IF(derived_messages.toid = '$user', derived_messages.fromid,
derived_messages.toid) friend1,c.UserName,
derived_messages.message, derived_messages.fromid, derived_messages.toid,
derived_messages.is_read,derived_messages.type,derived_messages.id as mesid,
derived_messages.date,
(SELECT M.message_id FROM messagesmapped M where M.message_id= derived_messages.id AND M.user_id ='$user' AND M.important = 1) as MesMapid
FROM
(
SELECT *
FROM messages
WHERE messages.deleted_by NOT
IN ( $user )
ORDER BY Date DESC
) derived_messages
INNER JOIN Users c ON c.MemberID = IF(derived_messages.toid = '$user', derived_messages.fromid,
derived_messages.toid)
WHERE (derived_messages.id IN
(SELECT M.message_id FROM messagesmapped M where M.message_id= derived_messages.id AND M.user_id ='$user' AND M.important = 1)
AND
(derived_messages.toid='$user' OR derived_messages.fromid='$user'))
GROUP BY friend1 ASC
ORDER BY derived_messages.date DESC, derived_messages.id DESC LIMIT $limit $offset
I hope someone can help m on this.
Thank you.
It's possible but unlikely someone will write the query for you.
My recommendation on tackling such a query is to write each individual subquery as its own Zend_Db_Select object and then build the final query using the subqueries that you already have objects for.
Zend_Db_Select doesn't directly support the IF function, so for that you will need to use Zend_Db_Expr to add that statement into your select.
Here is a basic example of what I am talking about. Let's build the following query:
SELECT IF(msg.toId = 'drew010', msg.fromId, msg.toId), id, name, age, history.ip
FROM users
JOIN history ON users.id = history.userId
WHERE users.id = (
SELECT id FROM users WHERE loginCount > 1000
)
GROUP BY id,
ORDER BY age DESC
First build the subselect that select users where loginCount > 1000.
$subquery1 = $db->select()
->from('users', array('id'))
->where('loginCount > ?', 1000);
Next, build the outer query with the IF function:
$cols = array(
new Zend_Db_Expr('IF(' . $db->quoteInto('msg.toId = ?', 'drew010') . '), msg.fromId, msg.toId'),
'id', 'name', 'age'
);
$query = $db->select()
->from('users', $cols)
->join('history', 'users.id = history.userId', array('ip'))
->where('id = ?', $subquery1)
->group('id')
->order('age DESC');
echo $query;
The output:
SELECT
IF(msg.toId = 'drew010', msg.fromId, msg.toId),
`users`.`id`,
`users`.`name`,
`users`.`age`,
`history`.`ip`
FROM `users`
INNER JOIN `history`
ON users.id = history.userId
WHERE id = (
(SELECT `users`.`id`
FROM `users`
WHERE (loginCount > 1000))
)
GROUP BY `id`
ORDER BY `age` DESC
So the way to go is break the entire query into individual queries first, and then construct the outer query. Just have patience and take it slow. That and read over the Zend_Db_Select docs to get a full picture of what you have available to you.

How Can I use Alias in Where

This is my code but it's not working:
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)'
)))
->where('x = ?', 'value');
// Alternatively use columns('p.product_name')
How can I retrieve x and compere it in where clause?
This is the actual query:
SELECT `abstract_submission`.*,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM mamba_event.abstract_submission_reviewer reviewer INNER JOIN
mamba_account.account_user user ON user.id = reviewer.userId
WHERE reviewer.submissionId = mamba_event.abstract_submission.id AND
user.isEnabled = 1)
AS `reviewers`,
(SELECT GROUP_CONCAT(CONCAT(author.firstName, " ", author.lastName) SEPARATOR ",")
FROM mamba_event.abstract_author author INNER JOIN
mamba_event.abstract_submission_author map ON author.id = map.authorId
WHERE map.submissionId = mamba_event.abstract_submission.id)
AS `allAuthors`,
(SELECT COUNT(`abstract_paper`.`id`) FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id`)
AS `numPapers`,
(SELECT `paperNumber` FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id` AND
`abstract_paper`.`currentStatus` = 3 LIMIT 1)
AS `acceptedPaperNumber`,
(SELECT IF ((COUNT(1) > 0), 'Paper has been uploaded','None') AS hasUploadedPaper
FROM `mamba_event`.`abstract_paper` paper
WHERE paper.submissionId = `mamba_event`.`abstract_submission`.`id`)
AS `hasUploadedPaper`,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM `mamba_event`.`abstract_submission_reviewer` reviewer INNER JOIN
`mamba_account`.`account_user` user ON user.id = reviewer.userId
WHERE reviewer.submissionId = `mamba_event`.`abstract_submission`.`id`
AND reviewer.hasConflictOfInterest = 1
AND user.isEnabled = 1)
AS `reviewersWithConflict`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_submission_score`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageScore`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_paper_score`, `mamba_event`.`abstract_paper`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averagePaperScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_submission_score` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON `criteriaId` = `abstract_request_criteria`.`id`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageWeightedScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_paper_score` JOIN
`mamba_event`.`abstract_paper` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON
`criteriaId` = `abstract_request_criteria`.`id`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averageWeightedPaperScore`, `author`.`email`
AS `authorEmail`, `author`.`salutation`
AS `authorTitle`, `author`.`firstName`
AS `authorFirstName`, `author`.`lastName`
AS `authorLastName`, `author`.`organisation`
AS `authorOrganisation`, `author`.`position`
AS `authorPosition`, `author`.`department`
AS `authorDepartment`, `author`.`phone`
AS `authorPhone`, `author`.`fax`
AS `authorFax`, `address`.`line1`
AS `addressLine1`, `address`.`line2`
AS `addressLine2`, `address`.`line3`
AS `addressLine3`, `address`.`line4`
AS `addressLine4`, `address`.`city`
AS `addressCity`, `address`.`stateCode`
AS `addressStateCode`, `address`.`countryCode`
AS `addressCountryCode`, `address`.`postalCode`
AS `addressPostalCode`, `author`.`biography`
AS `authorBiography`, `request`.`title`
AS `request`, `request`.`blindReview`, `request`.`hasCustomTypes`, `file`.`content_type`, `file`.`original_filename` AS `filename`, `author`.`speakerId`,
(SELECT GROUP_CONCAT(
CONCAT('',ifnull(author.firstName,'-'),' ',
ifnull(author.lastName,'-'),'
(',ifnull(author.organisation,'-'),',
',ifnull(author.authorCountryCode,'-'),')')
SEPARATOR ",")
FROM `mamba_event`.`abstract_author` author LEFT JOIN
`mamba_event`.`abstract_submission_author` sa
ON sa.authorId = author.id
WHERE sa.submissionId = `abstract_submission`.`id`)
AS `authorDetails`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2185'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2185`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2335'
AND `field`.`fieldValue` = 'BSCS'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2335`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2336'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2336` FROM `mamba_event`.`abstract_submission`
INNER JOIN `mamba_event`.`abstract_request` AS `request` ON requestId = request.id
LEFT JOIN `mamba_account`.`account_file` AS `file` ON fileId = file.id
INNER JOIN `mamba_event`.`abstract_author` AS `author` ON `presenterId` = `author`.`id`
LEFT JOIN `mamba_general`.`address` ON `author`.`addressId` = `address`.`id` WHERE ((`abstract_submission`.`isEnabled` = '1') AND (`abstract_submission`.`eventId` = '1893')) AND (`field2335` LIKE "%BSCS%") ORDER BY `request` asc LIMIT 15
You could do it with HAVING, like Muhammad Zeeshan said.
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)')))
->having('x = ?', 'value');

Categories