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();
Related
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();
I'm using codeigniter;
I would like to get last N rows from my table.
In my query I want to get last 200 rows:
$this->m_general->select('count(*)');
$this->m_general->from('pm');
$result_count_query = $this->m_general->get();
$count_query = $result_count_query->num_rows();
$data['all'] = $this->m_general->get('pm', array( 'admin_delete'=>0 ) , $count_query-200,$count_query, array('admin_seen'=>'asc' , 'id'=>'desc') );
but it returns nothing.
where is my wrong ?
updated
below query not worked fine and it returns all records :
$data['all'] = $this->m_general->get('pm', array( 'admin_delete'=>0 ) ,200, array('admin_seen'=>'asc' , 'id'=>'desc') );
This Solve the Problem
$query = $this->db->query("SELECT * FROM pm WHERE admin_delete= 0 AND admin_seen=0 ORDER BY id DESC LIMIT 200");
$result = $query->result_array();
$count = count($result);
if(empty($count))
{
echo 'array is empty';
}
else{
return $result;
}
Check out the API
https://ellislab.com/codeigniter/user-guide/database/active_record.html
Looks like you can't do this with the get method.
Build your query according to the API.
$this->m_general->limit(200);
$this->m_general->order_by("admin_seen", "asc");
$this->m_general->order_by("id", "desc");
$data['all'] =
$this->m_general->get('pm', array( 'admin_delete'=>0 ));
This is my problem: MySQL "Or" Condition
The solution is to group the OR statements, but i'm using CodeIgniters Active Record. Is there a way to group OR statements using Active Record? Or do I have to write the query myself?
I'm using $this->db->where() with $this->db->or_where()
It writes the query like this:
WHERE title = 'foobar' AND category = 2 OR category = 3
but what I need is:
WHERE title = 'foobar' AND (category = 2 OR category = 3)
I can't do this:
$this->db->where("title = 'foobar' AND (category = 2 OR category = 3)");
because i'm adding ORs using a foreach loop
You can do it manually as stated here:
Custom string: You can write your own clauses manually:
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
As for your question:
$this->db->where("category = 1 AND (category = 2 OR category = 3)");
In 3.0-dev:
$this->db->select()
->group_start()
->or_like([ 'category' => 2, 'category' => 3 ])
->group_end()
->where([ 'category' => 1 ]);
update
See the answers on this question if you're using CI 2.2. Choose an answer other than the accepted.
Or simply try this:
$categories = array(2, 3);
array_walk($categories, function(&$cat) { $cat = 'category = ' . $cat; });
$catstring = implode(" OR ", $categories);
$where = "category = 1 AND ($catstring)";
// => category = 1 AND (category = 2 OR category = 3)
$this->db->where($where);
as OP mentioned you are generating OR using foreach (array)
you can simply use
$cat_array=array(2,3,4,5,6,7);
$this->db->select('col1, col2')->from('table')->where("col1",1)->where_in('col2', $cat_array);
will generate
SELECT `col1`, `col2` FROM (`table`) WHERE `col1` = 1 AND `col2` IN (2, 3, 4, 5, 6, 7)
you can't manipulate ground condition query using DB active record methods (where, or_where) , i would recommond to pass as sting in where() method
$this->db->where("category = 1 AND (category = 2 OR category = 3)");
In the Code Igniter Version 3.0-dev you can add groups in any query using group_start and group_end :
$this->db->select('col1, col2')
->where("category = 1")
->group_start()
->where("category = 2")
->or_where("category = 3")
->group_end();
Produces:
SELECT `col1`, `col2`
FROM `table_name`
WHERE category = 1 AND (category = 2 OR category = 3);
I can't imagine how to select custom content from DB with active records. My code:
$select = array('mixed' => 'WHERE id = 2 OR id = 5');
$query = $this->db->select('*');
$query = $this->db->query($select['mixed']);
$query = $this->db->order_by('id DESC');
$query = $this->db->get($table);
query returns me:
0.0001 WHERE id = 2 OR id = 5
0.0002 SELECT * FROM po_posts_content ORDER BY id DESC
so how to make it right?
UPDATE:
changed $this->db->query($select['mixed']); to $this->db->where($select['mixed']);
and all worked FINE
You can use
$this->db->where_in('id', array(2,5));
or
$this->db->where('id =2 or id =5');
I tried myself for another queries but this one is more complex for me as i am new to zend. Please help me i tried different ways but not worked.
Tour Id fetching from another query
$tourId = $row2 ['test_public_id'];
$query = select count(ms.test_public_id) as total_views, ms1.recent_views from test_stats
ms join (select count(test_stats.test_public_id) as recent_views
from test_stats where test_stats.test_public_id = '$tourId'
and test_stats.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)) ms1
where ms.test_public_id ='$tourId'" ;
Something like that should work:
$subselect = $dbAdapther->select()->from(
array('test_stats' => 'test_stats'),
array(
'(COUNT(test_public_id)) AS recent_views'
)
)->where(
$dbAdapther->quoteInto('test_stats.test_public_id = ?', $tourId)
)->where(
'test_stats.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)'
);
$select = $dbAdapther->select()->from(
array('ms' => 'test_stats'),
array(
'(COUNT(ms.test_public_id)) AS total_views' // COUNT should be in brackets to preevent Zend from interpreting it as a field name
)
)->join(
array('ms1' => $subselect),
'',
array(
'ms1.recent_views'
)
)->where(
$dbAdapther->quoteInto('ms.test_public_id = ?', $tourId)'
);
Although I'd have your query broken into two separate ones or, more precisely, write a universal "get number of views" query with a date as its parameter, and then I'd be calling it twice, with or without the date.
But if you still need to get those two figures in one go in a single row (i.e. you can't use UNION instead of your unnecessary JOIN), I'd recommend you to use the following code instead:
$select = $dbAdapther->select()->from(
array('ms' => 'test_stats'),
array(
'(COUNT(ms.test_public_id)) AS total_views',
'(
COUNT(
CASE
WHEN ms.updated_on > DATE_SUB(CURDATE(), INTERVAL 7 DAY)) THEN ms.test_public_id
ELSE NULL
END
)
) AS recent_views'
)
)->where(
$dbAdapther->quoteInto('ms.test_public_id = ?', $tourId)
);
I'm new too in Zend, but I've tried this sample and it's works.
See this tutorial, I hope it'll help you:
http://framework.zend.com/manual/en/zend.db.select.html
or you can do this:
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$stmt = $db->query($query);
$result = $stmt->fetchAll();