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.
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 have the following getListQuery() in my model. I want to add another join (see further) and was wondering if the level part could be done another way (without GROUP_CONCAT):
protected function getListQuery()
{
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select(
$this->getState(
'list.select',
'a.id AS id,' .
'a.dbid AS dbid,' .
'a.alias AS alias,' .
'GROUP_CONCAT(DISTINCT l.level ORDER BY l.level ASC) as `levels`'
)
);
$query->from('#__maintable AS a');
$query->join('LEFT', '#__leveltable AS l ON l.dbid = a.dbid');
$query->group($db->quoteName('a.id'));
$query->order($db->escape($this->state->get('list.ordering', 'a.id') . ' ' . $db->escape($this->state->get('list.direction', 'ASC'))));
return $query;
}
In the leveltable there can be more then one row with a corresponding 'dbid'.
I would also like to add a second table which has a relation to 'dbid' which also can have multiple rows with the same 'dbid' and it has more fields I would require then just the 'level' field from leveltable.
I want to run an UPDATE query on a record after selecting it.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select(array('p.*', 'u.id', 'u.name' ,'pr.*'))
->from($db->quoteName('#__chichi_photos', 'p'))
->join('LEFT', $db->quoteName('#__users', 'u') . ' ON (' . $db->quoteName('p.userID') . ' = ' . $db->quoteName('u.id') . ')')
->join('LEFT', $db->quoteName('#__chichi_profile', 'pr') . ' ON (' . $db->quoteName('pr.userID') . ' = ' . $db->quoteName('u.id') . ')')
->where($db->quoteName('p.id') .'=' . $photoID .'');
$db->setQuery($query);
$results = $db->loadRow();
I want to run an UPDATE query on a field in #__chichi_photos table that has an id in the result and if possible do it with a single query statement.
Basically what i want to do is update "hits" column on the field after it is selected. Thank You.
I have a PHP file which is taking in seven variables like so:
$name=$_REQUEST['membername'];
$email=$_REQUEST['email'];
$dob=$_REQUEST['dob'];
$gender=$_REQUEST['gender'];
$phone=$_REQUEST['phone'];
$county=$_REQUEST['county'];
$IP=$_REQUEST['IP'];
Some of these will not be set. What I want to do is construct a query which will search the members table such that if only $email and $dob are set it will only search by $email and $dob, ignoring the others. Or if only $phone, $name, and $gender are set, it will search those three columns only.
Is there an easier method than constructing a big block of if isset functions covering all possible permutations?
If you don't want to search on a field, pass NULL for the parameter and structure your WHERE clause something like...
WHERE
( (#parameter1 IS NULL) OR (column1 = #parameter1) )
AND
( (#parameter2 IS NULL) OR (column2 = #parameter2) )
I don't spend much time in MYSQL so the syntax is probably a bit off but you get the idea.
Presuming that you use parameters to push values into the query...
SELECT *
FROM MyTable
WHERE name = COALESCE(#p1, name)
OR email = COALESCE(#p2, email)
OR dob = COALESCE(#p3, dob)
...
...
If you construct a query string in PHP you can, instead, take another tack:
function AddWhere(&$where, $dbFieldName, $fieldValue)
{
if ($fieldValue <> "")
{
if (strlen($fieldName) > 0)
$fieldName .= " AND ";
$fieldname .= '(' + $dbFieldName + ' = \'' + $fieldValue + '\')'
}
}
Then, when you're retrived the variables, build a SQL statement thusly
$whereClause = ''
AddWhere($whereClause, 'name', $name)
AddWhere($whereClause, 'email', $email)
AddWhere($whereClause, 'dob', $dob)
...
IF (strlen($whereClause) > 0)
{
$sql = 'SELECT * FROM MyTable WHERE ' + $whereClause
... etc
}
(I'm not great at PHP, so the syntax may be somewhat screwed up).
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 ;