phpcodeigniteractiverecordsql-likestartswith

How to implement a "starts with" LIKE condition with CodeIgniter's like() method


When I want to create the following line in CodeIgniter:

SELECT * FROM Customers WHERE City LIKE '%es%'; // CONTAINS 'es'

I write this code:

$this->db->select('*');
$this->db->from('Customers');
$this->db->like('City', 'es');

Could you please help me to write the relevant code for the following SQL?

SELECT * FROM Customers WHERE City LIKE 'ber%'; // STARTS WITH 'ber'

It should return rows where city values start with 'ber'.


Solution

  • You can use a third parameter to define where the wildcard will go:

    $this->db->like('City', 'es', 'after');
    //SELECT * FROM Customers WHERE City LIKE 'ber%'
    
    $this->db->like('City', 'es', 'before');
    //SELECT * FROM Customers WHERE City LIKE '%ber'
    
    $this->db->like('City', 'es', 'both'); //Default
    //SELECT * FROM Customers WHERE City LIKE '%ber%'