I am using the following code to select from a MySQL database with a Code Igniter webapp:
$query = $this->db->get_where('mytable',array('id'=>10));
This works great! But I want to write the following MySQL statement using the CI library?
SELECT * FROM `mytable` WHERE `id`='10' OR `field`='value'
Any ideas?
Thanks!
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
You can use or_where() for that - example from the CI docs:
$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);
// Produces: WHERE name != 'Joe' OR id > 50
You can use this :
$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);
Active record method or_where is to be used:
$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
Though I am 3/4 of a month late, you still execute the following after your where clauses are defined... $this->db->get("tbl_name");
What worked for me :
$where = '';
/* $this->db->like('ust.title',$query_data['search'])
->or_like('usr.f_name',$query_data['search'])
->or_like('usr.l_name',$query_data['search']);*/
$where .= "(ust.title like '%".$query_data['search']."%'";
$where .= " or usr.f_name like '%".$query_data['search']."%'";
$where .= "or usr.l_name like '%".$query_data['search']."%')";
$this->db->where($where);
$datas = $this->db->join(TBL_USERS.' AS usr','ust.user_id=usr.id')
->where_in('ust.id', $blog_list)
->select('ust.*,usr.f_name as f_name,usr.email as email,usr.avatar as avatar, usr.sex as sex')
->get_where(TBL_GURU_BLOG.' AS ust',[
'ust.deleted_at' => NULL,
'ust.status' => 1,
]);
I have to do this to create a query like this :
SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;
Related
I have this query:
$query = City::query();
$query->select('id', 'name as default_name', 'translations->' . $request["lang"] . ' as name', 'country_id');
$query->where(function ($query) use ($request) {
$query->whereRaw('LOWER(translations->"$.' . $request["lang"] . '") like ?', "'%" . strtolower($request['search']) . "%'");
$query->orWhere('name', 'like', "'%" . strtolower($request->search) . "%'");
});
if ($request->country !== null) {
$query->whereRaw('country_id = '. $country);
}
$results = $query->get();
That translates to this SQL:
select `id`, `name` as `default_name`, json_unquote(json_extract(`translations`, '$."en"')) as `name`, `country_id`
from `cities`
where (LOWER(translations->"$.en") like '%barcelona%' or `name` like '%barcelona%')
and country_id = 207
Eloquent is not returning any records while SQL does:
Any clue on whats wrong here?
Thanks!
Is Ok the part?
if ($request->country !== null) {
$query->whereRaw('country_id = '. $country);
}
Its seems like
if ($request->country !== null) {
$query->where('country_id', $request->country);
}
And in the select part the JSON column not has $ operator.
This line in the code seemed to be the problem:
$query->orWhere('name', 'like', "'%" . strtolower($request->search) . "%'");
I found a solution using orWhereRaw():
$query->orWhereRaw('LOWER(`name`) LIKE ? ','%'. trim(strtolower($request['search'])) .'%')
This line converts column "name" data to lowercase and trims and lowers the search parameter.
I hope it help others in the future.
I am running problems in implementing LIKE in PDO
I have this query:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);
I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.
The result is none returned. Do my $query is syntactically correct?
You have to include the % signs in the $params, not in the query:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
If you'd look at the generated query in your previous code, you'd see something like SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%', because the prepared statement is quoting your values inside of an already quoted string.
Simply use the following:
$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
OR address LIKE CONCAT('%', :var2, '%')";
$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
No, you don't need to quote prepare placeholders. Also, include the % marks inside of your variables.
LIKE ?
And in the variable: %string%
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
You can see below example
$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
Hope it will work.
I followed Joomla doc about how to select data from a single table. I need 3 OR conditions.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('column1', 'column2', 'column3' )));
$query->from($db->quoteName('#__table_example'));
$query->where($db->quoteName('column1') . ' LIKE '. $db->quote('condition1'));
OR where column2 == condition2
...
How to make where statement with many ORs in my example? I didn't find any topics on syntax correctness.
You just have to add or conditions in the same where statement :
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('column1', 'column2', 'column3' )));
$query->from($db->quoteName('#__table_example'));
$query->where($db->quoteName('column1') . ' LIKE '. $db->quote('condition1') . ' OR ' . $db->quoteName('column2') . ' LIKE '. $db->quote('condition2') . ' OR ' . $db->quoteName('column3') . ' LIKE '. $db->quote('condition3') );
I give a general answer which will cover not only OR but also several AND problems. Use WHERE query like this:
ex: query should run if one of (cond1 or cond2 or cond3) is true AND one of (cond4 or cond5 is true):
$query->where( ( (cond1)OR(cond2)OR(cond3) ) AND ( (cond4)OR(cond5) ) );
So you can use OR and AND any how you like, just be sure that you use () properly to define your condition.
In your particular case, you will use format like this:
$query->where( (var LIKE cond1) OR (cond2) );
obviously your cond2 is: column2 == condition2
I hope it resolves confusion.
Allright, i see that without 1st line, the second query will not work. But I don't understand why. Why its not working without SET? What set does mean ?
$query = "update messages set $name=$name+1 where id='$idd'";
$db->setQuery( $query );
$db->query( $query ) or die('blogai');
$query2 = "select up,down from messages where id='$idd'";
$db->setQuery( $query2 );
$db->query( $query2 ) or die('blogai');
Check your sql request in your database query editor :
select up,down from messages where id='yourValue'
I'm producing a query like the following using ActiveRecord
SELECT * FROM (`foods`) WHERE `type` = 'fruits' AND
`tags` LIKE '%green%' OR `tags` LIKE '%blue%' OR `tags` LIKE '%red%'
The number of tags and values is unknown. Arrays are created dynamically. Below I added a possible array.
$tags = array (
'0' => 'green'.
'1' => 'blue',
'2' => 'red'
);
Having an array of tags, I use the following loop to create the query I posted on top.
$this->db->where('type', $type); //var type is retrieved from input value
foreach($tags as $tag):
$this->db->or_like('tags', $tag);
endforeach;
The issue: I need to add parentheses around the LIKE clauses like below:
SELECT * FROM (`foods`) WHERE `type` = 'fruits' AND
(`tags` LIKE '%green%' OR `tags` LIKE '%blue%' OR `tags` LIKE '%red%')
I know how to accomplish this if the content within the parentheses was static but the foreach loop throws me off..
From the CI wiki:
The codeignighter ActiveRecord feature
allows you to create SQL queries
relatively simply and
database-independant, however there
isno specific support for including
parenthesis in an SQL query.
For example when you want a where statement to come out simmilarly to the folowing:
WHERE (field1 = value || field2 = value) AND (field3 = value2 || field4 = value2)
This can be worked around by feeding a string to the CI->db->where() function, in this case you will want to specifically escape your values.
See the following example:
$value=$this->db->escape($value);
$value2=$this->db->escape($value2);
$this->db->from('sometable');
$this->db->where("($field = $value || $field2 = $value)");
$this->db->where("($field3 = $value2 || $field4 = $value2)");
$this->db->get();
A simmilar workaround can be used for LIKE clauses:
$this->db->where("($field LIKE '%$value%' || $field2 LIKE '%$value%')");
$this->db->where("($field3 LIKE '%$value2%' || $field4 LIKE '%$value2%')");
In the CI 3.0-dev you can add groups in query:
$this->db->select('id, title')
->group_start()
->or_like([ 'title' => $s, 'id' => $s ])
->group_end()
->where([ 'b_del' => 0 ]);
Produces:
SELECT `id`, `title`, `venda1`
FROM `itens`
WHERE
(
`title` LIKE '%a%' ESCAPE '!'
OR `id` LIKE '%a%' ESCAPE '!'
)
AND `b_del` =0
One of best feature to save your query when you applying multiple where or_where clauses.
$this->db->group_start();
$this->db->where();
$this->db->or_where();
$this->db->group_end();
Happy Coding. :)
Going off of The Silencer's solution, I wrote a tiny function to help build like conditions
function make_like_conditions (array $fields, $query) {
$likes = array();
foreach ($fields as $field) {
$likes[] = "$field LIKE '%$query%'";
}
return '('.implode(' || ', $likes).')';
}
You'd use it like this:
$search_fields = array(
'field_1',
'field_2',
'field_3',
);
$query = "banana"
$like_conditions = make_like_conditions($search_fields, $query);
$this->db->from('sometable')
->where('field_0', 'foo')
->where($like_conditions)
->get()
Just adding my successful solution:
$this->db->where("(table.field = $variable OR table.field IS NULL)");
use codeigniter 3
$this->db->select('*');
$this->db->from($this->MasterMember);
$this->db->group_start();
$this->db->where($this->IDCardStatus, '1');
$this->db->or_where($this->IDCardStatus, '2');
$this->db->group_end();
if ($searchKey1 != null) {
$this->db->group_start();
$this->db->like($this->MemberID, $searchKey1);
$this->db->or_like($this->FirstName, $searchKey2);
$this->db->or_like($this->LastName, $searchKey3);
$this->db->group_end();
}
$this->db->limit($limit, $offset);
$data = $this->db->get();
this is my native query
SELECT
*
FROM
`Member`
WHERE ( `Member`.`IDCardStatus` = '1' OR `Member`.`IDCardStatus` = '2' )
AND ( `Member`.`MemberID` LIKE '%some_key%' ESCAPE '!' OR `Member`.`FirstName` LIKE '%some_key%' ESCAPE '!' OR `Member`.`LastName` LIKE '%some_key%' ESCAPE '!' )
LIMIT 10
Update for codeigniter 4:
$builder->select('*')->from('my_table')
->groupStart()
->where('a', 'a')
->orGroupStart()
->where('b', 'b')
->where('c', 'c')
->groupEnd()
->groupEnd()
->where('d', 'd')
->get();
// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'
from official docs on: https://codeigniter.com/user_guide/database/query_builder.html#query-grouping
$likes = array (
'0' => 'green'.
'1' => 'blue',
'2' => 'red'
);
$where_like = "(";
$or_counter = 1;
foreach($likes as $like_key => $like_val):
$or_content = ($or_counter > 1) ?'OR': '';
$newlikeval = $this->db->escape_like_str($like_val);
$where_like .= $or_content." `$like_key` LIKE '%$newlikeval%' ";
$or_counter++;
endforeach;
$where_like .= ")";
$this->db->where($where_like);
You can't add parentheses in ActiveRecord, but maybe WHERE IN is what you're looking for?
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')