Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a LIKE query with CodeIgniter?

I want to run a query like this:

SELECT * FROM table WHERE field LIKE '%search_term%'

In CI you can bind parameters to queries, if you used field=? but this does not work for field LIKE "%?%". From debugging output it seems the query used is field LIKE "%'search'%".

Is there an alternative way to do searching in CodeIgniter?

like image 758
DisgruntledGoat Avatar asked Sep 19 '10 14:09

DisgruntledGoat


People also ask

How do I print a query in CI?

Use the below query to display the query string: print_r($this->db->last_query()); To display the query result follow this: print_r($query);

What is query Builder in codeigniter?

CodeIgniter gives you access to a Query Builder class. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action.

How do I print last query?

We can get last executed query using last_query() function of db class in codeigniter. It is a very simple to use $this->db->last_query() function to see SQL statements of last executed query in php codeigniter app.


3 Answers

You can use this query:

SELECT * FROM table WHERE field LIKE ?

And bind with %search% instead of search.

You should be aware that this query will be slow in MySQL. You might want to look at free-text search instead (Lucene, Sphinx, or MySQL's built-in free-text search functions).

like image 112
Mark Byers Avatar answered Oct 24 '22 07:10

Mark Byers


this is active record class for codeigniter

$this->db->select('*');
$this->db->like('columnname','both');
$query=$this->db->get("tablesname");
$result=$query->result_array();
if(count($result))
{
return $result;
}
else
{
return FALSE;
}

You should try this..I think its help you.. both means %columnname%, before means %columnname, after means columnname%

like image 29
Snap Mash Avatar answered Oct 24 '22 05:10

Snap Mash


$search_term=$this->input->post('textboxName');
$search_term="%".$search_term."%";
$sql="SELECT * FROM table WHERE field LIKE ? ";
$query=$this->db->query($sql,array($search_term));
$res=$query->result();
like image 25
dulaj sanjaya Avatar answered Oct 24 '22 06:10

dulaj sanjaya