I am trying to retrieve data from table using codeigniter.
doing something like that:
....
$this->db->where('course_request.enrollment_policy !=', '2');
//I want to write next statements something like:
$this->db->if_where('course_request.enrollment_policy ', '3')
then
$this->db->where('course_request.status', '3');
else
other codeigniter where_in
Hope you got my problem.
Looking for solution, Thanks in advance.
Solved.
who says it is not possible in CI?
$this->db->where('(CASE WHEN `course_request`.`enrollment_policy` = 3 THEN `course_request`.`status` = "3" ELSE course_request.status="0" OR course_request.status = "3" END )' , NULL,FALSE);
Just paste this in your where :
AND (
CASE
WHEN `course_request`.`enrollment_policy` = 3
THEN `course_request`.`status` = '3'
ELSE 1=1
END
)
and give second param NULL , third param FALSE
Related
Hello I am a beginner in using Codeigniter. What I want is to update a data in Codeigniter with an OR condition to the ID.
Here is my MySQL query that I want to make happen:
Update message_received SET is_read = 1 WHERE msg_id = 3 OR parent_id = 3
I tried something like this:
$this->query->update_array('message_received', array('msg_id' => $_POST['read_my_message'],'parent_id' => $_POST['read_my_message']) , array('is_read'=>1));
You can use or_where to apply OR condition in CodeIgniter, I've written a possible solution for your question(Reference).
See if it helps you.
$msg = $this->input->post('read_my_message'); // get the post data
$this->db->set('is_read', 1); // set the value of column
$this->db->where('msg_id', $msg); // first condition
$this->db->or_where('parent_id', $msg); // second contion
$this->db->update('message_received'); // table name
// Produces:
/* UPDATE `message_received` SET `is_read` = 1 WHERE `msg_id` = '$msg' OR `parent_id` = '$msg' */
You can apply OR. The references https://www.codeigniter.com/userguide3/database/query_builder.html
im new to laravel, I just want to know if there's any way to efficiently rewrite this code?
$answer1 = SurveyAnswer::where('answer_1','=','1')->get()->count();
$answer2 = SurveyAnswer::where('answer_1','=','2')->get()->count();
$answer3 = SurveyAnswer::where('answer_1','=','3')->get()->count();
$answer4 = SurveyAnswer::where('answer_1','=','4')->get()->count();
$answer5 = SurveyAnswer::where('answer_1','=','5')->get()->count();
Get the data first:
$answers = SurveyAnswer::whereIn('answer_1', [1, 2, 3, 4, 5])->get();
Then count answers using loaded collection:
$answer1 = $answers->where('answer_1', 1)->count();
$answer2 = $answers->where('answer_1', 2)->count();
...
This code will generate just one DB query instead of five.
Try this:
$matches = [1,2,3,4,5];
$answer = SurveyAnswer::whereId('answer_1', $matches)->groupBy('answer_1')->get();
You can easily do it with an agregate function with a case expression, since mysql doesnot support native pivoting functions
Following is a sample, and try to rewrite according to your requirement and runt it against database directly, if it works, then you can use it with laravel raw sql.
select id,
sum(case when value = 1 then 1 else 0 end) ANSWER1_COUNT,
sum(case when value = 2 then 1 else 0 end) ANSWER2_COUNT
from survey
group by answer
I have a custom validation rule that is checking the DB for NULL.
I need to look for null or empty.
HAVE:
$query = $this->db()->table($table);
...
foreach( $null_columns as $col )
$query->where_null($col);
Which results in something like: SELECT * FROM t WHERE col1=foo AND col2 IS NULL
WANT:
SELECT * FROM t WHERE col1=blah AND (col2 = '' OR col2 IS NULL)
QUESTION:
Is where-nested() the right tool for the job?
If so, I'd really like to see an example.
If not, what's a good way to approach this?
Well, I ended up getting it to work this way:
$query = $this->db()->table($table);
...
foreach( $null_columns as $col )
{
$query->where(function($q) use($col){
$q->where($col,'=','');
$q->or_where_null($col);
});
}
... but would still like to see an example of using where_nested() to do this, if possible. I always appreciate learning something new :)
I'm trying to do this:
SELECT
userId, count(userId) as counter
FROM
quicklink
GROUP BY
userId
HAVING
count(*) >= 3'
In doctrine with the querybuilder, I've got this:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
Which gives me this error:
[Semantical Error] line 0, col 103 near 'HAVING count(*)': Error: Cannot group by undefined identification variable.
Really struggling with doctrine. :(
Your SQL is valid, Your query builder statement is invalid
All cause db will execute that query in following order:
1. FROM $query = $this->createQueryBuilder('q')
2. GROUP BY ->groupby('userId') // GROUP BY
3. HAVING ->having('counter >= 3')
4. SELECT ->select('userId, count(userId) as counter')
So as You can see counter is defined after its use in having.
Its SQL Quirk. You can not use definitions from select in where or having statements.
So correct code:
$query = $this->createQueryBuilder('q')
->select('userId, count(userId) as counter')
->groupby('userId')
->having('count(userId) >= 3')
->getQuery();
return $query->getResult();
Do note repetition in having from select
I am going to answer for people who still have this type of error.
First things first, you seem to have translated a native sql query inside a query builder object. More so, you have named your object as q
$query = $this->createQueryBuilder('q');
What this means, in general, is that every condition or grouping etc you have in your logic should address fields of q: q.userId, q.gender, ...
So, if you had written your code like below, you would have avoided your error:
$query = $this->createQueryBuilder('q')
->select('q.userId, count(q.userId) as counter')
->groupby('q.userId')
->having('counter >= 3')
->getQuery();
return $query->getResult();
I think you are missing the 'from' statement
$query = "t, count(t.userId) as counter FROM YourBundle:Table t group by t.userId having counter >1 ";
return $this->getEntityManager()->createQuery($query)->getResult();
This should work. You can even do left joins or apply where clausules.
you can define HAVING parameter via setParameter() method as well
$qb->groupBy('userId');
$qb->having('COUNT(*) = :some_count');
$qb->setParameter('some_count', 3);
Hey.. I've run into a problem using several "like" in my sql-query (generated with Codeigniter's activerecord):
SELECT * FROM (`posts`) WHERE `city` LIKE '%test%' AND `title` LIKE '%%' OR `text` LIKE '%%'
Thing is, it appears to read this query as if there was a parenthesis around the first like and the second like, but I want there to be a parenthesis around the second and the last like (I want it to compare if the last or the next to last works).
How can I achieve this using Codeigniter's Active Record class?
Current code:
if($type != 0)
$this->db->where('type', $type);
$this->db->like('city', $area);
$this->db->like('title', $words);
$this->db->or_like('text', $words);
return $this->db->get('posts')->result_array();
Previous answer is correct. I would like to add the following...
In Codeigniter supporting the following overall...
$this->db->like();
$this->db->or_like();
$this->db->not_like();
$this->db->or_not_like();
Hope this will help someone.
I don't think CI is adding any paranthesis. It will add an 'AND' between the first two statements and an 'OR' between the last two. To achieve what you want, I would write my own statement. It's very straightforward.
$sql = SELECT * FROM 'posts' WHERE city LIKE ? AND ( title LIKE ? OR text LIKE ? );
$query = $this->db->query($sql, array($area, $words, $words));
Notice how I've used binding. This automatically escapes characters for you.
this will do the trick
$this->db->select('*')->from('my_table')
->group_start()
->where('a', 'a')
->or_group_start()
->where('b', 'b')
->where('c', 'c')
->group_end()
->group_end()
->where('d', 'd')
->get();
// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
when you have to use table join as well try following method
public function get_all_airports($para) {
$this->db->select('airports.name as air_name, airports.city, airports.type, airports.home_link, country.name as con_name');
$this->db->from('airports');
$this->db->join('country', 'airports.iso_country = country.code', 'inner');
$this->db->where("airports.type !=", "small_airport");
$this->db->where("airports.type !=", "closed");
$this->db->where("airports.type !=", "heliport");
$this->db->where("airports.type !=", "medium_airport");
$this->db->where("airports.type !=", "seaplane_base");
$where = "(country.name LIKE '%$para%' OR airports.city LIKE '%$para%')";
$this->db->where($where);
echo json_encode($this->db->limit(20)->get()->result());
}