full text search in codeigniter - codeigniter

I have a query to search keywords using like, but I also want to search full text so I changed it to full text search query, but it doesn't work.
The old query that's working fine:
$data = $this->db
->select('content.title,content.id,content.category,content.body,path')
->from('content')
->join('categories','content.category = categories.id')
->like('content.title', $searchterm)
->like('content.body', $searchterm)
->order_by("content.id","DESC")
->get();
and this is my new query for full text search:
$data = $this->db
->select('content.title,content.id,content.category,content.body,path')
->from('content')
->join('categories','content.category = categories.id')
->where('MATCH (content.body, content.title) AGAINST ("'. $searchterm .'")')
->order_by("content.id","DESC")
->get();

if you are using mysql version 5.5 or lower, make sure all the tables involved have the engine MyISAM.
make sure the your column has the FULLTEXT INDEX.
where() takes 3 arguments, example:
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
$this->db->get('table');
more than one columns in match() triggers Error Number: 1191, so separate them:
->where('MATCH (content.title) AGAINST ("'. $searchterm .'")')
->where('MATCH (content.body) AGAINST ("'. $searchterm .'")')

Try by changing the where clause in your query, see if it helps:
->where('MATCH (content.body, content.title) AGAINST ("'. $searchterm .'")', NULL, false)
This sets the value to NULL and tells CI not to escape the string.

you did not use the correct syntax of mathch .... against
try this:
->where MATCH (content.body, content.title) AGAINST ("'. $searchterm .'") > 0

if you have multiple column you can use them in single line like this:
->where("MATCH(title, model) AGAINST('$text')", null, false);
or just one column:
->where("MATCH(title) AGAINST('$text')", null, false);
don't forget to escape your inputs. because we disabled escaping with that false over there. use this for escaping:
$text = $this->db->escape_str($text);

Related

Codeigniter Query binding multiple fields with the same value

I'm in a situation where I'm doing a MySQL query with Codeigniter and where I have a lot of fields value request which are ALL the same.
Example:
$this->db->query('SELECT * FROM abc WHERE user_id = ? AND msg_from = ? AND msg_to != ?', [$id, $id, $id]);
This has just 3 question marks but the query I'm working on is HUGE and has 19 question marks WHICH ARE ALL THE SAME variable.
So I was trying to figure out how to tell Codeigniter all question marks are pointing to the same variable without having to fill an array with 19 times the same variable.
I thought of a for-loop but I wanted to know if a shortcut exist.
you should be able to do this with Codeigniters Query Builder pretty easily
Something like that should work:
$this->db
->select('*')
->from('abc');
$arrFields = array('users_id', 'msg_from', 'msg_to');
foreach($arrFields AS $val)
{
$this->db->where($val, $id);
}
$query = $this->db->get();

What is the equivalent query of laravel on this?

This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here

Laravel Date comparison not working in Eloquent query

I do not understand why but following query return null resultset.
due_date is Carbon date and $now=Carbon:today();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>=',$now)
->where('due_date','<',$now->addMonth())
->get();
Also when I use whereBetween it doesn't work.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$now, $now->addMonth()])
->get();
But when I just to greater than or lesser than it works
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>',$now->addWeek())
->get();
What am I missing here?
The problem here is that you are using the same instance for both range limits. When you call addMonth you add the month to the instance stored in $now. The two examples below illustrate the issue:
1. Using and modifying the same variable in two separate statements works as you'd expect:
$now = Carbon::now();
dump($now); // prints 2015-12-12 14:50:00.000000
dump($now->addMonth); // prints 2016-01-12 14:50:00.000000
2. Using the same variable and modifying it in the same statement that passes the values to a method, will work differently, because it will be evaluated before being passed to the method. Meaning that both parameters will be equal because they both contain the same instance from the $now variable, which after getting evaluated will contain the DateTime of one month from now.
$now = Carbon::now();
// Calling `addMonth` will change the value stored in `$now`
dump($now, $now->addMonth());
// The above statement prints two identical DateTime values a month from now:
// 2016-01-12 14:50:00.000000 and 2016-01-12 14:50:00.000000
This means that your current code was checking if the entries were due only exactly one month from now.
To fix it you need to use two instances in two separate variables:
$from = Carbon::now();
$to = Carbon::now()->addMonth();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$from, $to])
->get();
It looks like it is because I used '$now' in the query.
Like is said before the query I did $now=Carbon::today(); and use $now in the query.
But then I got rid of that and changed the query to use Carbon::today() it worked.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[Carbon::today(), Carbon::today()->addMonth())
->get();
It is weird.
Thanks,
K

CodeIgniter like query with single quote in search string

I have been working on this for like more than 4 hours. I have select query using active record I am doing: $this->db->like ('items.name',$search);
everything works fine but whenever there is single quote (') in the $search string it gives this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's%' OR default_items.short LIKE 'faith\'s%' LIMIT 5' at line 5
I have just checked now that it is adding double back slashes \\ instead of single in my active record for LIKE query. I tried in MySQL bt removing one slash and it is working.
My code:
$q = "faith's";
$query = $this->db->select('items_categories.slug as category_slug, items_categories.name as cat_name, items.name, items.price_value, items.cover_photo, items.slug');
$query->select('default_items.short as short',false);
$query->select('date(default_items.date_created) as date_created',false);
$query->join('items_categories','items_categories.id=items.root_id','inner');
$query->join('users','items.company_id=users.id','inner');
$query->like('items.name',$q);
$query->or_like('items.short',$q);
$query->limit(5);
$result = $query->get($this->_table);
$both_prod_results = $result->result();
I am using pyrocms 2.x.
You can try the following code maybe it can help you, but you have to add \ before every' in your requests :
$value = "faith\'s";
$sql_request = "`short` LIKE '%". $value ."%'";
$query = $this->db
->select('*')
->where($sql_request, null, false)
->get('default_items');
$result = $query->result();
dump($result);
i think i need to answer my own question.
Well this is a hack(don't think if it is secure)
I have patched my MYSQLI Driver:
i have replaced this:
return str_replace(array($this->_like_escape_chr, '%', '_'),
array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
$str);
with this:
return str_replace(array($this->_like_escape_chr, '%', '_'),
array($this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
$str);
it was adding extra slash. and also don't think it will allow sql injections etc anything.
if anyone knows this is right then please comment.
Thanks
Umair

CodeIgniter query syntax error

I am facing a syntax issue with a CodeIgniter database query. Can't figure out what's wrong.
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES (".$this->db->escape($_POST['email']).", ".$this->db->escape($lang).", ".$this->input->ip_address().")");
I am also looking for a way to output what the query looks like once the placeholders are replaced, as I am little confused with CodeIgniter debugging options.
It looks as though you are not escaping the strings that you're trying to input into the database. The query you've posted would evaluate to something like:
$query = $this->db->query("
INSERT IGNORE INTO table_name (email, lang, ip_address)
VALUES (email#email.com, en, 192.168.0.1)
");
This will throw an error as the strings in VALUES are not properly escaped. Instead of the query you're running you should use something like:
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')
");
Note the new ' characters around each string.
use
echo $this->db->last_query();
for retrieving the query runned.
so then check if the query is well formatted.
To know what query you are passing to your database. Use below statement and to insert data into the database. Please follow the below procedure.
echo $this->db->last_query();
$data = array(
'email' => $this->db->escape($_POST['email']),
'lang' = > $this->db->escape($lang),
'ip_address' => $this->input->ip_address(),
);
Call your model function $this->model->insert_function_name($data);
Your model function in your model file
public function insert_function_name($data)
{
$this->db->insert($table_name,$data);
return $this->db->insert_id();
}
Try this : your query was missing single quotes to the string type of value like email, lang and ip
$query = $this->db->query("
INSERT IGNORE INTO ".$table." (email, lang, ip_address)
VALUES ('".$this->db->escape($_POST['email'])."', '".$this->db->escape($lang)."', '".$this->input->ip_address()."')");

Resources