How to use SOUNDS LIKE in where clause - mysql

Codeigniter Active records query gives me error. how to put SOUNDS LIKE into where clause.
function _search($type, $q, $qes, $sort = null, $start = 0) {
$type = strtolower($type);
$q = strtolower($q);
$this->db->select("*");
$this->db->from("books");
$this->db->where("SOUNDEX(name) IN({$q})");
foreach($qes as $k){
$this->db->or_where("name SOUNDS LIKE '$k'");
}
foreach($qes as $k){
$this->db->or_where("name LIKE '%$k%'");
}
$this->db->where("status", 1);
if ($type != NULL) {
$this->db->where("LOWER(type)", $type);
}
//$this->db->like("LOWER(name)", $q);
$this->db->limit(BWK_MAX_BOOK_SIZE, $start);
switch ($sort) {
case 1:
break;
case 2:
$this->db->order_by("sellingPrice", "ASC");
break;
case 3:
$this->db->order_by("sellingPrice", "DESC");
break;
case 4:
$this->db->order_by("created", "DESC");
break;
}
this gives me query when i echo query. i am searching for technologi i need to get technology technologies etc.
SELECT * FROM `books` WHERE SOUNDEX(name) IN('t254') OR `name` `SOUNDS` LIKE 'technolog' OR `name` LIKE '%technologi%' AND `status` = 1 AND LOWER(type) = 'school' LIMIT 50
getting error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`SOUNDS` LIKE 'technolog' OR `name` LIKE '%technolog%' AND `status` = 1 AND LOWE' at line 4
every thing works fine but when i put SOUNDS LIKE it gives me error.

its probably the best to group things here
you can try the following
$this->db
->select('*')
->from('books')
->where_in('SOUNDEX(name)', $q, NULL);
if (is_array($qes) && count($qes) > 0)
{
$this->db->group_start();
foreach($qes AS $k)
{
$this->db->or_group_start();
$this->db
->where('name SOUNDS LIKE '.$this->db->escape($k), NULL, false)
->or_like('name', $k);
$this->db->group_end();
}
$this->db->group_end();
}
if (!is_null($type))
{
$this->db->where('LOWER(type)', $type);
}
switch ($sort) {
case 1:
break;
case 2:
$this->db->order_by("sellingPrice", "ASC");
break;
case 3:
$this->db->order_by("sellingPrice", "DESC");
break;
case 4:
$this->db->order_by("created", "DESC");
break;
}
echo $this->db
->where('status',1)
->limit(BWK_MAX_BOOK_SIZE, $start)
->get_compiled_select();
this would produce a statement like
SELECT *
FROM `books`
WHERE SOUNDEX(name) IN('t254') AND
(
(
name SOUNDS LIKE 'technologi' OR
`name` LIKE '%technologi%' ESCAPE '!'
)
OR
(
name SOUNDS LIKE 'whatever' OR
`name` LIKE '%whatever%' ESCAPE '!'
)
)
AND `status` = 1
AND LOWER(type) = 'school'
LIMIT 50

From : DB_query_builder.php, what one can see is 3rd argument decides whether to escape or not.
public function or_where($key, $value = NULL, $escape = NULL){
}
So just tell that not to escape it
$this->db->or_where("name SOUNDS LIKE '$k'", NULL, FALSE);

Could you use the HAVING clause with your ORDER BY and your LIKE?
HAVING clause:
https://www.w3schools.com/sql/sql_having.asp

Related

Getting SQL query Syntax error or access violation while running raw SQL in yii2

am trying to creating a search function to be able to search for products and also filter the result by relevance but i got Syntax error after the query.
below is the error i got too
sql error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'mens', 'winter', 'jacket'%',6,0) + if (title LIKE '%'mens'%',5,0) + if (title LI' at line 5
The SQL being executed was: SELECT p.product_id,p.title,p.price,p.unit_sold,
p.profile_img,p.store_name,p.item_number,
(
(-- Title score
if (title LIKE '%'mens', 'winter', 'jacket'%',6,0) + if (title LIKE '%'mens'%',5,0) + if (title LIKE '%'winter'%',5,0) + if (title LIKE '%'jacket'%',5,0)
)+
(-- description
if (description LIKE '%'mens', 'winter', 'jacket'%',5,0) + if (description LIKE '%'mens'%',4,0) + if (description LIKE '%'winter'%',4,0) + if (description LIKE '%'jacket'%',4,0)
)
) as relevance
FROM products p
WHERE p.is_active = '1'
HAVING relevance > 0
ORDER BY relevance DESC,p.unit_sold DESC
LIMIT 10
and the search function
function search($q){
if (mb_strlen(trim($q))===0){
// no need for empty search
return false;
}
$query = $this->limitChars(trim($q));
// Weighing scores
$scoreFullTitle = 6;
$scoreTitleKeyword = 5;
$scoreFullDescription = 5;
$scoreDescriptionKeyword = 4;
$keywords = $this->filterSearchKeys($query);
$escQuery = $this->escape($keywords);
$titleSQL = array();
$descSQL = array();
/** Matching full occurences **/
if (count($keywords) > 1){
$titleSQL[] = "if (title LIKE '%".$escQuery."%',{$scoreFullTitle},0)";
$descSQL[] = "if (description LIKE '%".$escQuery."%',{$scoreFullDescription},0)";
/** Matching Keywords **/
foreach($keywords as $key){
$titleSQL[] = "if (title LIKE '%".Yii::$app->db->quoteValue($key)."%',{$scoreTitleKeyword},0)";
$descSQL[] = "if (description LIKE '%".Yii::$app->db->quoteValue($key)."%',{$scoreDescriptionKeyword},0)";
}
//add 0 is query string is empty to avoid error
if (empty($titleSQL)){
$titleSQL[] = 0;
}
if (empty($descSQL)){
$descSQL[] = 0;
}
$sql = "SELECT p.product_id,p.title,p.price,p.unit_sold,
p.profile_img,p.store_name,p.item_number,
(
(-- Title score
".implode(" + ", $titleSQL)."
)+
(-- description
".implode(" + ", $descSQL)."
)
) as relevance
FROM products p
WHERE p.is_active = '1'
HAVING relevance > 0
ORDER BY relevance DESC,p.unit_sold DESC
LIMIT 10";
$results = Yii::$app->db->createCommand($sql)->queryAll();
if (!$results){
return false;
}
return $results;
}
I'm also using escape() method to escape the query string in other to avoid sql injection but am not so convince this is the best practice as what the escape method does is adding single quote around the string which in turn will not even return any match in the table, I also try to use mysqli_escape_string() but can't get it work either, so i want to know what's the best practice in Yii2 to escape query string and avoid sql injection attack.
function escape($values)
{
$values = (array)$values;
$escaped = array();
foreach($values as $value) {
if(!is_scalar($value)) {
throw new CException('One of the values passed to values() is not a scalar.');
}
$escaped[] = Yii::$app->db->quoteValue($value);
}
return implode(', ', $escaped);
}
You should escape the whole expression for LIKE, including % wildcards:
$value = Yii::$app->db->quoteValue('%' . implode(', ', (array) $keywords) . '%');
$titleSQL[] = "if (title LIKE $value,$scoreFullTitle,0)";
This will generate something like:
if (title LIKE '%mens, winter, jacket%',6,0)

MySql multiple times Where in Condition if possible

i am Performing the MySQL query with Where In conditions.
Here is my Query.
The query should be:
SELECT * FROM users WHERE id IN (44,44,33,44,33,0);
Query showing my correct result, no problem at all,
but what i want to do is Can we Divide all the id with the individual conditions ?
Or can a query has multiple Where In for a single column?
like
SELECT * FROM users WHERE id IN (44)
AND id IN (45)
AND id IN (46);
like this.
Is that possible ? ?
My query code for performing the query, its in Laravel.
$films = Film::with('genre')->with('languages')->with('likes')->with('comments')->with('likedBy');
if(Input::get('sort')){
$sort = Input::get('sort');
switch ($sort){
case 'old_new':
$films = $films->orderBy('created_at', 'asc');
break;
case 'new_old':
$films = $films->orderBy('created_at', 'desc');
break;
case 'views':
// $films = DB::table('films')
// ->leftJoin('film_views', 'films.id', '=', 'film_views.film_id')
// ->select(DB::raw('films.*, count(film_views.film_id) as views'))
// ->groupBy('films.id')
// ->orderBy('views' , 'desc')
// ;
$films = $films
->leftJoin('film_views', 'films.id', '=', 'film_views.film_id')
->select(DB::raw('films.*, count(film_views.film_id) as views'))
//->whereBetween('created_at', [$this->first_day_of_search, $this->final_day_of_search])
->groupBy('films.id')
->orderBy('views' , 'desc')
;
break;
case 'likes':
$films = $films
->leftJoin('film_likes', 'films.id', '=', 'film_likes.film_id')
->select(DB::raw('films.*, count(film_likes.film_id) as likes'))
->groupBy('films.id')
->orderBy('likes' , 'desc')
;
break;
}
}
if(Input::get('filter')) {
$jsonFilter = Input::get('filter');
$filters = json_decode($jsonFilter);
foreach ($filters as $filter => $value){
switch ($filter){
case "genre":
if($value){
$films = $films->whereHas('genre', function ($query) use($value) {
$query->whereIn('genre_id', $value);
});
}
break;
case "cert":
if($value){
$films = $films->whereIn('cert', $value);
}
break;
case "country":
if($value){
$films = $films->whereIn('country', $value);
}
break;
case "lang":
if($value){
$films = $films->whereHas('languages', function ($query) use($value) {
$query->whereIn('language_id', $value);
});
}
break;
}
}
}
$films = $films->paginate(5);
return parent::api_response($films->toArray(), true, ['return' => 'all films'], 200);
I will post an answer if for no other reason than amusement. I believe that a WHERE IN clause is internally converted into a series of equality onditions separated by OR. So your original query
SELECT * FROM users WHERE id IN (44,44,33,44,33,0)
would be internally converted to this
SELECT * FROM users WHERE id = 44 OR id = 44 OR id = 33 OR id = 44 OR
id = 33 OR id = 0
So having a single number for your IN clause would be equivalent to a single equality condition.
By the way, you have the same numbers appearing multiple times, which doesn't make any sense.
Yes, it is possible to have multiple WHERE IN.
SELECT * FROM users WHERE id IN (44) OR id IN (45) OR id IN (46);
This is correct.
However I don't understand why you want to do this because this is low in performance compared to having one IN

PDO multiple LIKE causes; how to?

function searchPaste($string, $err=false)
{
global $sql;
$buffer = $err?"SELECT * FROM `pastes` WHERE `exposure` = 'public' AND `title` LIKE ? OR `paste` LIKE ? OR `lang` LIKE ?":"SELECT * FROM `pastes` WHERE `exposure` = 'public' AND `title` LIKE ?";
echo $buffer."<br>";
$buffer = $sql->prepare($buffer);
$buffer->execute(array(sprintf("%%%s%%", $string)));
if(!$buffer->rowCount()>0)
return 0;
return $buffer->fetchAll(PDO::FETCH_OBJ);
}
As you see in my first query I am matching by multiple cases problem is "?" is only handled once and I'm unsure how I could go about using an array to do this for all causes.
Anyone know what I could do?
You need to provide a bind value / param for each placeholder in your query. You're going to have to do away with the ternary I think. You could try something like this...
$buffer = "SELECT * FROM `pastes` WHERE `exposure` = 'public' AND `title` LIKE ?";
$paramCount = 1;
if (!$err) {
$buffer .= ' OR `paste` LIKE ? OR `lang` LIKE ?';
$paramCount += 2;
}
$stmt = $sql->prepare($buffer);
$stmt->execute(array_fill(0, $paramCount, "%$string%"));
function searchPaste($string, $err=false)
{
global $sql;
$sql->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$query = "SELECT * FROM `pastes` WHERE `exposure` = 'public' AND (`title` LIKE :search";
if ($err) {
$query .= " OR `paste` LIKE :search OR `lang` LIKE :search";
}
$query .= ")";
$stmt = $sql->prepare($query);
$stmt->execute(array("search" => "%$string%")));
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
finally got the logic and fixed the query.

Codeigniter parentheses in dynamic Active Record query

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')

CodeIgniter: How to use WHERE clause and OR clause

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 ;