Avoid backticks from CI query - php

My code is
public function getbonexpense($yr=null)
{
$this->db->select('year(un_due_date) as year,month(un_due_date) as month,sum(coalesce(bank_amount,0) +amount) as bonsum');
$this->db->from('bon_expense');
$this->db->join('bank_expense','bon_expense.id_bon_exp = bank_expense.bon_exp_id', 'left');
$this->db->where('expense_status',3);
$this->db->group_by('year(un_due_date)');
$this->db->group_by('month(un_due_date)');
if(!empty($yr))$this->db->where('year(un_due_date)',$yr);
$this->db->order_by('month(un_due_date)','desc');
$query = $this->db->get();
if($query->num_rows() != 0)
return $query->result_array();
else
return false;
}
but automatically insert codes(`) in running query
SELECT year(un_due_date) as year, month(un_due_date) as month, sum(coalesce(amount, 0)+coalesce(bank_amount, **`0))`** as bonsum
FROM (`crm_bon_expense`)
LEFT JOIN `crm_bank_expense` ON `crm_bon_expense`.`id_bon_exp` = `crm_bank_expense`.`bon_exp_id`
WHERE `expense_status` = 3
AND year(un_due_date) = '2014'
GROUP BY year(un_due_date), month(un_due_date)
ORDER BY month(un_due_date) desc
The single backticks comes in the sum () fuction.How can i avoid it?

add 2nd param FALSE in db -> select method, see below sample code
$this->db->select('year(un_due_date) as year,
month(un_due_date) as month,
sum(coalesce(bank_amount,0) +amount) as bonsum', FALSE);
Documentation:
https://ellislab.com/codeigniter/user-guide/database/active_record.html#select

Related

How to order row by specific value? MySQL CodeIgniter

I have a issue.
My sql query don't work in codeigniter, when i try to order by specific value
Here's example:
$this->db->select('*');
$this->db->from('Questions');
$this->db->where('Questions.Status !=', 0);
$this->db->order_by('IdQuestion', 'DESC');
$this->db->order_by('(CASE WHEN Status = 3 THEN 1 ELSE 2 END)', 'DESC'); //Here's wrong...
But i don't receive valid result.
Someone can help.
Second order_by statement is wrong.
CASE don't work correct.
You can try this solution for your problem :
<?php
$sub_query_from = '(SELECT Questions.*, (CASE WHEN Questions.Status = 3 THEN 1 ELSE 2 END) as questions_status from Questions WHERE Questions.Status != 0 ORDER BY IdQuestion DESC) as sub_questions';
$this->db->select('sub_questions.*');
$this->db->from($sub_query_from);
$this->db->order_by('sub_questions.questions_status', 'DESC');
$query = $this->db->get();
$result = $query->result();
echo "<per>";
print_r($result);
exit;
?>
Hope it will helps.
My solutions is that:
To create view which will contains all results ordered, before select this view in codeigniter model
Example:
select (case when (`parajurist`.`intrebari`.`Status` = 2) then 1 else 2 end)
AS `Second`,`parajurist`.`intrebari`.`IdIntrebare` AS
`IdIntrebare`,`parajurist`.`intrebari`.`Titlu` AS
`Titlu`,`parajurist`.`intrebari`.`Descriere` AS
`Descriere`,`parajurist`.`intrebari`.`NumePrenumeP` AS
`NumePrenumeP`,`parajurist`.`intrebari`.`EmailP` AS
`EmailP`,`parajurist`.`intrebari`.`Status` AS
`Status`,`parajurist`.`intrebari`.`IdCategorie` AS
`IdCategorie`,`parajurist`.`intrebari`.`DataAdresare` AS
`DataAdresare`,`parajurist`.`intrebari`.`Comments` AS
`Comments`,`parajurist`.`intrebari`.`CuvCheie` AS `CuvCheie` from
(`parajurist`.`intrebari` join `parajurist`.`intrebaricategorii`
on((`parajurist`.`intrebaricategorii`.`IdCategorie` =
`parajurist`.`intrebari`.`IdCategorie`))) where
(`parajurist`.`intrebari`.`Status` <> 0) order by (case when
(`parajurist`.`intrebari`.`Status` = 2) then 1 else 2
end),`parajurist`.`intrebari`.`IdIntrebare` desc
and codeigniter code:
$this->db->limit($start, $stop);
$this->db->select('*');
$this->db->select('LEFT(intrebari_view.Titlu, 50) as Titlu');
$this->db->select('LEFT(intrebari_view.Descriere, 150) AS Descriere');
$this->db->join('IntrebariCategorii', 'IntrebariCategorii.IdCategorie = intrebari_view.IdCategorie');
$this->db->where('IntrebariCategorii.NumeCategorie', $cat);
$this->db->from('intrebari_view');
$query = $this->db->get();

How can I achieve a UNION query using Codeigniter's active records? [duplicate]

How to do UNION query with PHP CodeIgniter framework's active record query format?
CodeIgniter's ActiveRecord doesn't support UNION, so you would just write your query and use the ActiveRecord's query method.
$this->db->query('SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2');
By doing union using last_query(), it may hamper performance of application. Because for single union it would require to execute 3 queries. i.e for "n" union "n+1" queries. It won't much affect for 1-2 query union. But it will give problem if union of many queries or tables having large data.
This link will help you a lot: active record subqueries
We can combine active record with manual queries.
Example:
// #1 SubQueries no.1 -------------------------------------------
$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get();
$subQuery1 = $this->db->_compile_select();
$this->db->_reset_select();
// #2 SubQueries no.2 -------------------------------------------
$this->db->select('title, content, date');
$this->db->from('mytable2');
$query = $this->db->get();
$subQuery2 = $this->db->_compile_select();
$this->db->_reset_select();
// #3 Union with Simple Manual Queries --------------------------
$this->db->query("select * from ($subQuery1 UNION $subQuery2) as unionTable");
// #3 (alternative) Union with another Active Record ------------
$this->db->from("($subQuery1 UNION $subQuery2)");
$this->db->get();
This is a quick and dirty method I once used
// Query #1
$this->db->select('title, content, date');
$this->db->from('mytable1');
$query1 = $this->db->get()->result();
// Query #2
$this->db->select('title, content, date');
$this->db->from('mytable2');
$query2 = $this->db->get()->result();
// Merge both query results
$query = array_merge($query1, $query2);
Not my finest work, but it solved my problem.
note: I didn't need to order the result.
You may use the following method to get the SQL statement in the model:
$this->db->select('DISTINCT(user_id)');
$this->db->from('users_master');
$this->db->where('role_id', '1');
$subquery = $this->db->_compile_select();
$this->db->_reset_select();
This way the SQL statement will be in the $subquery variable, without actually executing it.
You have asked this question a long time ago, so maybe you have already got the answer. if not, this process may do the trick.
by modifying somnath huluks answer, i add these following variable and functions to DB_Active_rec class as follows:
class DB_Active_records extends CI_DB_Driver
{
....
var $unions;
....
public function union_push($table = '')
{
if ($table != '')
{
$this->_track_aliases($table);
$this->from($table);
}
$sql = $this->_compile_select();
array_push($this->unions, $sql);
$this->_reset_select();
}
public function union_flush()
{
$this->unions = array();
}
public function union()
{
$sql = '('.implode(') union (', $this->unions).')';
$result = $this->query($sql);
$this->union_flush();
return $result;
}
public function union_all()
{
$sql = '('.implode(') union all (', $this->unions).')';
$result = $this->query($sql);
$this->union_flush();
return $result;
}
}
therefore you can virtually use unions without dependencies to db_driver.
to use union with this method, you simply make regular active record queries, but calling union_push instead of get.
note: you have to ensure your queries have matching columns like regular unions
example:
$this->db->select('l.tpid, l.lesson, l.lesson_type, l.content, l.file');
$this->db->where(array('l.requirement' => 0));
$this->db->union_push('lessons l');
$this->db->select('l.tpid, l.lesson, l.lesson_type, l.content, l.file');
$this->db->from('lessons l');
$this->db->join('scores s', 'l.requirement = s.lid');
$this->db->union_push();
$query = $this->db->union_all();
return $query->result_array();
would produce:
(SELECT `l`.`tpid`, `l`.`lesson`, `l`.`lesson_type`, `l`.`content`, `l`.`file`
FROM `lessons` l
WHERE `l`.`requirement`=0)
union all
(SELECT `l`.`tpid`, `l`.`lesson`, `l`.`lesson_type`, `l`.`content`, `l`.`file`
FROM `lessons` l
JOIN `scores` s ON `l`.`requirement`=`s`.`lid`)
I found this library, which worked nicely for me to add UNION in an ActiveRecord style:
https://github.com/NTICompass/CodeIgniter-Subqueries
BUT I had to grab the get_compiled_select() method from the dev branch of CodeIgniter first (available here: https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_query_builder.php -- DB_query_builder will be replacing DB_active_rec). Presumably this method will be available in a future production release of CodeIgniter.
Once I added that method to DB_active_rec.php in system/database it worked like a charm. (I didn't want to use the dev version of CodeIgniter as this is a production app.)
try this one
function get_merged_result($ids){
$this->db->select("column");
$this->db->distinct();
$this->db->from("table_name");
$this->db->where_in("id",$model_ids);
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select("column2 as column");
$this->db->distinct();
$this->db->from("table_name");
$this->db->where_in("id",$model_ids);
$this->db->get();
$query2 = $this->db->last_query();
$query = $this->db->query($query1." UNION ".$query2);
return $query->result();
}
This is solution I am using:
$union_queries = array();
$tables = array('table1','table2'); //As much as you need
foreach($tables as $table){
$this->db->select(" {$table}.row1,
{$table}.row2,
{$table}.row3");
$this->db->from($table);
//I have additional join too (removed from this example)
$this->db->where('row4',1);
$union_queries[] = $this->db->get_compiled_select();
}
$union_query = join(' UNION ALL ',$union_queries); // I use UNION ALL
$union_query .= " ORDER BY row1 DESC LIMIT 0,10";
$query = $this->db->query($union_query);
bwisn's answer is better than all and will work but not good in performance because it will execute sub queries first.
get_compiled_select does not run query; it just compiles it for later run so is faster
try this one
$this->db->select('title, content, date');
$this->db->where('condition',value);
$query1= get_compiled_select("table1",FALSE);
$this->db->reset_query();
$this->db->select('title, content, date');
$this->db->where('condition',value);
$query2= get_compiled_select("table2",FALSE);
$this->db->reset_query();
$query = $this->db->query("$query1 UNION $query2");
Here's a solution I created:
$query1 = $this->db->get('Example_Table1');
$join1 = $this->db->last_query();
$query2 = $this->db->get('Example_Table2');
$join2 = $this->db->last_query();
$union_query = $this->db->query($join1.' UNION '.$join2.' ORDER BY column1,column2);

CodeIgniter Active Records where in subquery

How do I write where_in statement a subquery using codeigniter active records ?
$query = $this->db->query("SELECT SUM(a.transaction_payment_amount) FROM
transaction_payment a WHERE a.transaction_link IN
(SELECT transaction_link FROM transaction WHERE transaction_type = '22'");
$result = $query->result();
Now how to convert the above query into CI active records ?
I have tried:
$this->db->select("SUM(a.transaction_payment_amount)");
$this->db->from('transaction_payment a');
$this->db->where_in('a.transaction_link', "SELECT transaction_link from transaction WHERE transaction_type = '22'");
$query = $this->db->get();
$result = $query->result();
But it doesn't work.
Try This
$this->db->where_in('a.transaction_link', "SELECT transaction_link from transaction WHERE transaction_type = '22'",false);
if you use false then it will remove single quotes from where_in condition
Sharmas Answer should do the job but if you wish fully supported Query Builder Methods you can try this
$strSubQuery = $this->db
->select("transaction_link")
->from("transaction")
->where("transaction_type",22)
->get_compiled_select();
$query = $this->db
->select("SUM(a.transaction_payment_amount)", false)
->from('transaction_payment a')
->where_in('a.transaction_link', $strSubQuery, false)
->get();
You can change your code as following solution.
Changes your query
$this->db->select("SUM(a.transaction_payment_amount)");
$this->db->from('transaction_payment a');
$this->db->where("a.transaction_link IN (SELECT transaction_link from transaction WHERE transaction_type = '22')", null, false);
//OR you can try other where condition if Sub query return null value than used this below query
$this->db->where("IF(SELECT transaction_link from transaction WHERE transaction_type = '22',a.transaction_link IN (SELECT transaction_link from transaction WHERE transaction_type = '22'), NULL)", null, false);
$query = $this->db->get();
$result = $query->result();
I hope this will helps you. Thanks!

Codeigniter query returns false

I have a query that gets the schedule of a employee and display it in table. I sampled some employees with the default schedules but when I try to retrieve others that have different schedule, it always returns false meaning the table is empty. Here is the query that I made:
function get_Sked($id,$from,$to)
{
$query = "SELECT c.dt, a.TimeFrom,a.TimeTo FROM schedule a LEFT JOIN cal c ON a.SkedDate = c.dt AND a.EmpID = ? WHERE c.dt BETWEEN DATE(?) AND DATE(?) GROUP BY c.dt ORDER BY c.dt ASC";
$query = $this->db->query($query,array($id,$from,$to));
if($query->num_rows() == 0)
{
return false;
}
else
{
return $query->result_array();
}
}
and this is the method that calls it:
$data['sked'] = $this->DBmodel->get_Sked($id,$dFrom,$dTo);
if($data['sked'] == false)
{
echo "Default Schedule of 8:00 am to 5:00 pm."; //if table is empty show default sched.
var_dump($data['sked']);
}
else
{
foreach($data['sked'] as $val) //this will show the content of the table.
I am using the same query sequence as the others and not having problems only this one.....
I change my query structure to this:
$this->db->select('c.dt,a.TimeFrom,a.TimeTo');
$this->db->from('cal c');
$this->db->join('schedule a','a.SkedDate = c.dt');
$this->db->where('a.EmpID',$id);
$this->db->where('c.dt',$from);
$this->db->where('c.dt',$to);
$query = $this->db->get();
but returns false still....

Total amount is ok when i enter one record in both tables if i insert 2nd record in 2nd talble than total amount will double

Dear all friends i am new in Codeigniter framework i want total amount by selecting two table data, the problem is that when i enter data in 2nd table than total will double.
function total_amount($booking_no = NULL)
{
$data = array('forwarding_cargo_booking_details.*',
'other_charges.client_amount');
$this->db->select($data);
$this->db->where('forwarding_cargo_booking_details.booking_no',$booking_no);
$this->db->join('other_charges','forwarding_cargo_booking_details.booking_no = other_charges.booking_no','left');
$this->db->select('sum((`bk_m3`*`o_freight_client`)*(`selling_rate`)+`pod_client`+`thc_client`+`caf_client`+`baf_client`+`haulage_client`+`war_risk_client`+`warehouse_client`+`thc_dest_client`+`pp_surcharge_client`+`doc_charges_client`+`client_amount`) as salam', FAlSE);
$query = $this->db->get('forwarding_cargo_booking_details');
if($query->num_rows() > 0)
{
return $query->row();
}
}
Change it to this. Here use derieved query and test if it works ok
function total_amount($booking_no = NULL)
{
$sql_query = "SELECT
forwarding_cargo_booking_details.*,
other_charges.client_amount,
sum((`bk_m3`*`o_freight_client`)*(`selling_rate`)+`pod_client`+`thc_client`+`caf_client`+`baf_client`+`haulage_client`+`war_risk_client`+`warehouse_client`+`thc_dest_client`+`pp_surcharge_client`+`doc_charges_client`+`client_amount`) as amount
FROM forwarding_cargo_booking_details
LEFT JOIN (SELECT booking_no , sum(client_amount) FROM other_charges group by booking_no) as other_charges ON forwarding_cargo_booking_details.booking_no = other_charges.booking_no
";
$query = $this->db->query();
if($query->num_rows() > 0)
{
return $query->row();
}
}
use this code to print the query, and check the query.
$this->db->last_query();
i think you forget to use "Group By" in your query

Categories