简体   繁体   中英

How to select from Mysql comma separated values?

My Mysql table named company is below

id--username---countries

1---taner--------1,2,3
2---tom----------2,3
3---Jack---------1,3
4---Jenny--------1

I have a form and i post country from it.

<select name="country" >
<option value="1" >Turkey</option>
<option value="2" >England</option>
<option value="3" >USA</option>
</select>

And when i post the form and get the POST value of country.

$country=$_POST['country'];
SELECT * FROM company where country='$country';
..............................

My aim is fetching this query and listing the data belongs to post value, if England choosed taner and tom must list becuse England's option value is 2 and in my database only tom and taner contains this country value.

So what's your advice ?

Use MySQL's FIND_IN_SET() function.

Here's the reference:

So your query should be like this:

$query = "SELECT * FROM company WHERE FIND_IN_SET('$country', country)";

You can use Pattern Matching wild card operator to do this

SELECT * FROM company where country LIKE '%$country%';

Hope this work. But as per VR46 it not advice to use comma separated values in column.

您可以使用mysql的LIKE功能:

SELECT * FROM company WHERE country LIKE '%$country%';

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