简体   繁体   中英

how to search a certain part in one field on SQL?

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

order_billing
--------------
19001-00001-32222
13501-00021-31122
13344-02351-16072
18701-00001-30922
11123-12301-12122

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.?

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

$order_billing = $post['order_billing_1']."-".
                 $post['order_billing_2']."-".
                 $post['order_billing_3'];

You can then use this in a simple query.

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM