I'm doing some task using Codeigniter and i have a problem in query search. I have the following data in mysql:


it have 3 parts format for order_billing : number_1-number_2-number_3

and i make search form for like this

<input type="text" name="order_billing_1">-
<input type="text" name="order_billing_2">-
<input type="text" name="order_billing_3"> 

how do i can make a SQL query when for with condition

  • input "order_billing_1" for search "number_1"
  • input "order_billing_2" for search "number_2"
  • input "order_billing_3" for search "number_3"

i made some code like this

$post = $this->input->post();
$search['number_1'] = $post['order_billing_1'];
$search['number_2'] = "-".$post['order_billing_2'];
$search['number_3'] = "-".$post['order_billing_3'];

and the query like this

$this->db->like('order_billing', '$search['number_1']', 'after');
$this->db->or_like('order_billing', '$search['number_2']', 'both');
$this->db->or_like('order_billing', '$search['number_3']', 'before');

but it still not correct. i still confuse how to search like that in manual SQL query.

$search['number_1'] = $post['order_billing_1'];
$search['number_2'] = "-".$post['order_billing_2'];
$search['number_3'] = "-".$post['order_billing_3'];

the query

Select * from TABLE WHERE order_billing like ????

do any one know how to solve this.?

4 Answers

KIKO Software On

Why don't you make it into one long string?

$order_billing = $post['order_billing_1']."-".

You can then use this in a simple query.

Please note I used $post and not $_POST to mimic what you did.

O. Jones On

In plain SQL you want

SELECT * FROM TABLE WHERE order_billing = CONCAT('13344','-','02351','-','16072')

order_billing is a single column so needs to be searched with a single string. CONCAT() puts your three input fields into a single string. There are plenty of other ways to do that too.

Beware SQL injection. And think about normalization.

Salman A On

The SQL query could be written like this. It will match the values entered by the user and use a wildcard otherwise:

WHERE order_billing LIKE CONCAT_WS(
    IFNULL(NULLIF(:order_billing_1, ''), '%'),
    IFNULL(NULLIF(:order_billing_2, ''), '%'),
    IFNULL(NULLIF(:order_billing_3, ''), '%')

So if the user specified '1234', '', '5678' the query would match 1234-%-5678.

user1981712 On

like '%something%' searches 'something' between some other text

let's say you are searching for '1234'

for order billing 1 use -> like '1234-%' for order billing 2 use -> like '%-1234-%' for order billing 3 use -> like '%-1234'