I want to convert the following SQL query to codeIgniter active records format
SELECT * FROM `relation`
WHERE (`user1` = 144 OR `user2` = 144)
AND `status` = 2
AND `action` != 1
My attempt was something like this,
$ID=144;
$this->db->where('user1', $ID);
$this->db->or_where('user2', $ID);
$this->db->where('status', 2);
$this->db->where('action!=', 1);
However the results are not compatible. Can you point what is off here?
I would also be fine with suggestions not specifically using active records for the query.
the correct query would be
$query = $this->db
->select('*')
->from('relation')
->group_start()
->where('user1', $ID)
->or_where('user2', $ID)
->group_end()
->where('status', 2)
->where('action !=', 1)
->get();
As your are using OR between multiple condition you must have to enclosed this in bracket. Change your code as below:
$this->db->where('(user1', $ID,FALSE);
$this->db->or_where("user2 = $ID)",NULL,FALSE);
$this->db->where('status', 2);
$this->db->where('action!=', 1);
Hope this will help you :
$ID = 144;
$this->db->select('*');
$this->db->from('relation');
$this->db->where('user1', $ID);
$this->db->or_where('user2', $ID);
$this->db->where('status', '2');
$this->db->where('action !=', '1');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
print_r($result);
//return $query->result();
}
For more : https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data
Related
i am trying to fetch data from database table in between two dates and it is having two more filter using 'OR' clause but in result i am getting data either between date or data fetched using 'OR' clause.I am posting here query in model if anyone knows solution please let me know.
Thanks in advance
$this->db->select('*');
$this->db->from('Transaction');
$this->db->join('Users', 'Transaction.user_id = Users.id');
$this->db->where('date >=',$startDate);
$this->db->where('date <=',$endDate);
$this->db->where( 'against = Recharge');
$this->db->or_where('against =','Rech_Commission');
$query = $this->db->get();
return $query->result();
I want date filter compulsory but want to fetch records against=Recharge or against='Rech_commission'but i am getting either using date range or against='Rech_Commission'
use
$where = '(against="Recharge" or against = "Rech_Commission")';
$this->db->where($where);
and you had date and date and (against = '' or against = '')
$this->db->select('*');
$this->db->from('Transaction');
$this->db->join('Users', 'Transaction.user_id = Users.id');
$this->db->where('date BETWEEN "'. date('Y-m-d', strtotime($startDate)). '" and "'. date('Y-m-d', strtotime($endDate)).'"');
$this->db->where('against="Recharge" OR against = "Rech_Commission")';
$query = $this->db->get();
return $query->result();
$this->db->select('*');
$this->db->from('Transaction');
$this->db->join('Users', 'Transaction.user_id = Users.id');
$this->db->group_start();
$this->db->where('date >=',$startDate);
$this->db->where('date <=',$endDate);
$this->db->where( 'against = Recharge');
$this->db->group_end();
$this->db->or_where('against =','Rech_Commission');
$query = $this->db->get();
return $query->result();
I am trying to convert this query:
SELECT * FROM table WHERE condition1 = 'example' AND (date1 = 'date' OR renewal1 = 'renewal');
into CodeIgniter's Active Record format. I tried the following:
$q = $this->db->select('*');
$q = $this->db->from('table');
$q = $this->db->where('condition1 = condition');
$q = $this->db->where('date1 = date OR renewal = renewal');
$q = $this->db->get();
$results = $q->result();
But this did not have the desired affect. It seemed to not place the parenthesis around the second set of conditions, which caused the query to not work as expected. How else can I do this to represent what I want?
Thanks for the help!
You can use
$this->db->select('*');
$this->db->from('table');
$this->db->where('condition1 =',' condition');
$where = '(date1 = "date" OR renewal1 = "renewal")';// you can use your condition like this
$this->db->where($where);
$q = $this->db->get();
$results = $q->result();
I'm trying to...
Set some query parameters and filters.
Get the total number of matching rows.
Set limit and offset.
Get the results
Here's what I initially tried:
$this->db->select(<aggregation, subqueries>);
$this->db->from('users');
$this->db->where(<complex filters>);
$total = $this->db->count_all_results();
$this->db->limit($limit, $offset);
$query = $this->db->get();
$result = $query->result();
But calling count_all_results calls _reset_select internally meaning I have to do the first step again - not very DRY.
How would you achieve this in a simple, clean way?
Just use Query Builder Caching
$this->db->start_cache();
$this->db->select(<aggregation, subqueries>);
$this->db->from('users');
$this->db->where(<complex filters>);
$this->db->stop_cache();
$total = $this->db->count_all_results();
$this->db->limit($limit, $offset);
$query = $this->db->get();
$this->db->flush_cache();
$result = $query->result();
https://codeigniter-30-dev.readthedocs.io/zh_TW/latest/database/query_builder.html#this-db-count-all-results
im using active record, its all working ok but i want to set the $data["totalres"] to the total results, i mean, the same query but without the LIMIT
the problem is the previous statements gets unset when you do a query modifier, so i cant even add the $this->db->limit() after i get the results.
any ideas? i think its a bad practice to 'duplicate' the query just to do this
function get_search($start, $numrows, $filter = array())
{
...
$this->db
->select("emp")
->from('emp')
->join('empr', 'empr.b = empr.id', 'left')
->like('code', $code)
->limit($numrows, $start);
...
$q = $this->db->get();
// number of rows WITHOUT the LIMIT X,Y filter
$data["totalres"] = ???????;
if ($q->num_rows() > 0)
{
$data["results"] = $q->result();
} else {
$data["results"] = array();
}
return $data;
}
You can use SQL_CALC_FOUND_ROWS to get the number of rows that would have been returned sans-LIMIT. Note the ,FALSE in the select line. This tells CodeIgniter not to try to escape the SELECT clause with backticks (because SQL_CALC_FOUND_ROWS is not a field, and CodeIgniter doesn't realize that).
$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->from('emp')
->join('empr', 'empr.b = empr.id', 'left')
->like('code', $code)
->limit($numrows, $start);
$q = $this->db->get();
Then after that query is ran, we need run another query to get the total number of rows.
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["totalres"] = $query->row()->Count;
Try this:
function get_search($start, $numrows, $filter = array()){
$tmp= $this->db
->select("emp")
->from('emp')
->join('empr', 'empr.b = empr.id', 'left')
->like('code', $code)
->_compile_select();
$q= $this->db->limit($numrows, $start)->get();
// number of rows WITHOUT the LIMIT X,Y filter
$data["totalres"] = $this->db->query($tmp)->num_rows();
if ($q->num_rows() > 0){
$data["results"] = $q->result();
} else {
$data["results"] = array();
}
return $data;
}
I would actually suggest the use of CIs query caching.
To use this, you start the cache, build the query without the limits in place. Run your query to get the full count, then apply the limit and run the query to get your list for your page with the offset you need.
The cache will remember the variables that have been defined.
You can then clear the cache for subsequent queries.
Example
$this->db->start_cache();
// Where, like, having clauses in here
$this->db->stop_cache();
$count = $this->db->get('table')->num_rows();
$this->db->limit('limit', 'offset');
$result = $this->db->get('table')->result_array();
$this->db->flush_cache();
$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->from('emp')
->join('empr', 'empr.b = empr.id', 'left')
->like('code', $code)
->limit($numrows, $start); $q = $this->db->get();
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["totalres"] = $this->db->get()->row()->Count;
CodeIgniter 2.1.0 not run, below code will fix it.
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$objCount = $query->result_array();
$data["totalres"] = $objCount[0]['Count'];
I want to fetch that through model
SELECT `id`, `name`, `visits`, `shortdes`, `photo` FROM `products`
WHERE `name` LIKE '$word'
OR `shortdes` LIKE '$word' ANd `valid` = 1 ORDER BY `id` DESC
I used that, but it returned false
$this->db->order_by('id', 'desc');
$this->db->like('name', $word);
$this->db->or_like('shortdes', $word);
$this->db->where('valid', 1);
$this->db->select('id, name, visits, shortdes, photo');
$query = $this->db->get('products');
What can i use?
For debugging codeigniter's query builder query's, I usually reccommend doing something like this to debug them and see exactly what query the statements are producing.
$this->db->order_by('id', 'desc');
$this->db->like('name', $word);
$this->db->or_like('shortdes', $word);
$this->db->where('valid', 1);
$this->db->select('id, name, visits, shortdes, photo');
$query = $this->db->get('products');
echo "<pre>"
die(print_r($this->db->last_query(), TRUE));
When ran, it will output the actual raw SQL query being produced, and you can then debug it from there.
You should order your active record queries the same way you order a regular SQL query...
SELECT
WHERE
order_by
$this->db->get(x); -- which is the equivalent of FROM.
IE:
<?php
$this->db->select('id, name, visits, shortdes, photo');
$this->db->where('valid', 1);
$this->db->like('name', $word);
$this->db->or_like('shortdes', $word);
$this->db->order_by('id', 'DESC');
$query = $this->db->get('products');
if ($query->num_rows() > 0)
{
$row = $query->row();
echo $row->id;
echo $row->name;
echo $row->visits;
etcetc...
}
Or instead of using active records you can just use a full query.
$query = $this->db->simple_query('YOUR QUERY HERE');
Use the following user guide pages for more documentation:
active records:
http://codeigniter.com/user_guide/database/active_record.html
query results:
http://codeigniter.com/user_guide/database/results.html