How to order row by specific value? MySQL CodeIgniter - php

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

Related

User defined variable not working in Mysql Code Igniter

I am trying to rank the rows based on when was it lasted updated partitioned by category name.
$query = "SELECT
category_name,
topic_title,
updated_ts,
#topic_rank := IF(#current_category = category_name, #topic_rank + 1, 1) AS topic_rank,
#current_category := category_name AS current_category
FROM topic_master
ORDER BY category_name, updated_ts DESC
";
$data = $this->db->query($query);
if($this->db->affected_rows() > 0)
{
return $data;
}
else
{
return false;
}
This query runs perfectly fine in MySQL and gives me the topic_rank as 1,2,3 and so on.
When I run this in CodeIgniter, I get topic_rank as 1 for all records.
What could be the issue ?
Try to use codeigniger database methods result_array():
$q = $this->db->query($query);
$data = $q->result_array();
Found an alternate way to solve this problem. No idea why the user defined variable was not working.
select category_name, topic_title as last_topic, updated_ts as last_activity, topic_pri_key as last_topic_id from
(
select
a.category_name, a.topic_title,
a.updated_ts,
a.topic_pri_key,
count(b.updated_ts)+1 as rank
from
topic_master a
left join
topic_master b
on a.updated_ts < b.updated_ts and a.category_name = b.category_name
group by 1,2,3,4
) a
where rank = 1

How to use FIND_IN_SET in codeigniter query?

$array = array('classesID' => 6);
$this->db->select()->from($this->_table_name)->where($array)->order_by($this->_order_by);
$query = $this->db->get();
return $query->result();
I need to get the rows where the classesID is 6. Some rows contain 6,5,4.
so i need to use FIND_IN_SET query to retrive where the classesID is 6.
Please guide me
Thanks
I need to get the rows which has student id '4488' and message id '1418'
$id = 1418;
$student_id = 4488;
this->db->select('id, action_status, updated_on, student_ids');
$this->db->where('message_id', $id);
$this->db->where('find_in_set("'.$student_id.'", student_ids) <> 0');
$this->db->from('actions_history');
$query = $this->db->get();
It will return a query like
SELECT id, action_status, updated_on, student_ids FROM actions_history WHERE message_id = '1418' AND find_in_set("4488", student_ids) <>0
Try this
$array = array('classesID' => '5,6,7');
$this->db->select();
$this->db->from($this->_table_name);
$this->db->where("FIND_IN_SET('classesID',".$array['classesID'].")",null,false);
$this->db->order_by($this->_order_by);
$query = $this->db->get();
return $query->result();
You can write the query like this.
return $this->db->where('classesID' , '6')->order_by('column_name','desc')->get('table_name')->result_array();
if Need any help comment
For those who're looking for model (CI v4.x) based solution,
$modal->where("FIND_IN_SET('<string to find>', '<column name>')", null, false)->findAll();
In your case,
$modal->where("FIND_IN_SET('".$array['classesID']."', 'classesID')", null, false)->findAll();

or_where inside where function active records

I would like to ask if anyone of you know how to place a or_where inside a where in codeigniter?
I would like to create a query as shown below
select *
from table
where
(
(in = 0 and call_in = 1) or
(out = 0 and call_out = 1)
) and
mid = 0
ORDER BY id DESC
limit 1
I have created something like this
$result = $mysql_handler->select('*')
->from("table")
->where(
array(
"in" => 0,
"call_in" => 1
)
)
->or_where(
array(
"out" => 0,
"call_out" => 1
)
)
->where("mid", 0)
->order_by("id", "DESC")
->limit(1)
->get();
But I know this is not right since this code will produce something like this
select *
from table
where
(in = 0 and call_in = 1) or
(out = 0 and call_out = 1) and
mid = 0
ORDER BY id DESC
limit 1
I thinking of placing the or_where inside the where clause but I'm not sure if this is correct or how to do it. Please advice thanks.
You cannot combine where and or_where as you wanted. or_where can be used where only OR queries needed. You can try this for your solution
$this->db->from('table');
$this->db->select('*');
$this->db->where('((in = 0 and call_in = 1) OR (out = 0 and call_out = 1))');
$this->db->where("mid", 0);
$this->db->order_by("id", "DESC");
$this->db->limit(1);
$result=$this->db->get();
Or
$result = $mysql_handler->select('*')
->from("table")
->where('((in = 0 and call_in = 1) OR (out = 0 and call_out = 1))')
->where("mid", 0)
->order_by("id", "DESC")
->limit(1)
->get();

mysql query logic in codeigniter

I have two mysql tables memes and votes. Sample data is give below
Memes table
Votes table
vote = 1 is for upvote and vote = 0 is for downvote.
I want result something like this
To calculate up and down votes for each record.
Here is my code only for get records from memes table.
function loadAllMemes($categoryID,$sortby, $page,$perpage)
{
$data = array();
$this->db->select("*");
$this->db->from("memes");
$this->db->limit($perpage, $page);
if($categoryID > 0)
{
$this->db->where("categoryid",$categoryID);
}
if($sortby != "")
{
if($sortby == "recently")
{
$this->db->order_by("date","DESC");
}
else if($sortby == "popular")
{
$this->db->order_by("views","DESC");
}
}
$query = $this->db->get();
return $query->result();
}
Any help will be appreciated. Thanks
select Memes.*, sum(vote) upvote, sum(if(vote = 0, 1, 0)) downvote from memes
join vote on memes.id = memeid
group by memeid
This is not tried out. So kndly excuse if there is any syntax error
NOTE : This is purely in sql. Please do necessary things to convert for codeigneter
For Mysql you can directly put your condition us sum function and this will result a boolean 0/1 and you can use it your query as below
SELECT
m.*,
SUM(v.vote = 1) upvotes, /* this equal to SUM(CASE WHEN v.vote = 1 THEN 1 ELSE 0 END) */
SUM(v.vote = 0) downvote
FROM memes m
JOIN vote v ON m.id = v.memeid
GROUP BY m.id
For active record you can write above query as
$this->db->select('m.*,SUM(v.vote = 1) upvotes,SUM(v.vote = 0) downvote',FALSE)
->from('memes m')
->join('vote v','m.id = v.memeid ')
->group_by('m.id')
->get()
->result();
Quick solution would be by using subquery, although, I think join would be more efficient here.
SELECT
m.id,
m.title,
m.path,
m.date,
m.categoryid,
m.views,
(SELECT COUNT(*) FROM votes WHERE vote = '1' AND memeid = m.id) upvotes,
(SELECT COUNT(*) FROM votes WHERE vote = '0' AND memeid = m.id) downvotes
FROM memes m

Avoid backticks from CI query

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

Categories