Sanket Shinde
Sanket Shinde

Reputation: 134

Mysql query for Comma separated values in columns and aslo in search keywords

I have one condition in query where I want to search results. In database there is region column in which region is saved as comma separated. And user select multiple regions which I get in comma separated format. How can I compare column value and search values. I want query in codeigniter.

$search_id2 = "01,02,03";

$this->db->select('posting_id,short_desc, doc_last, country');
$this->db->from('abc');
$this->db->like('region', $search_id2);
$query = $this->db->get();

Upvotes: 0

Views: 277

Answers (2)

Atural
Atural

Reputation: 5439

as neodan suggested in the comments you can use find in set

something like that should do the job

$search_id2 = "01,02,03";
$arrSearchIds = explode(",",$search_id2);

$this->db
    ->select('posting_id,short_desc, doc_last, country')
    ->from('abc')
    ->group_start();

if (count($arrSearchIds) > 0)
{
    foreach($arrSearchIds AS $id)
    {
        $this->db->or_where("find_in_set(".$id.", region)", NULL, false);
    }
}
$this->db->group_end();
$query = $this->db->get();

Upvotes: 0

Gilang Pratama
Gilang Pratama

Reputation: 431

I just try to answer your problem. You can use explode()

$search_id2 = "01,02,03";
$search_id2 = explode(",",$search_id2)
$this->db->select('posting_id,short_desc, doc_last, country');
$this->db->from('abc');
foreach ($search_id2 as $key) {
    $this->db->or_like('region', $key);
}
$query = $this->db->get();

Upvotes: 0

Related Questions