0

I searched for questions like this.. But I could not find answer to fetch data from mysql table.

I have mysql table like below :

| id   |    division  | branch
|  1   |    Mumbai    | Thane
|  2   |    Mumbai    | Kalyan
|  3   |    Pune      | Nagar
|  4   |    Pune      | Sangamner
|  5   |    Solapur   | Jat
|  6   |    Solapur   | Satara

Now I have a comma separated string as follows

$string = Mumbai,Solapur

I want to fetch rows where division column contains Mumbai and Solapur

I tried FIND_IN_SET() but it doesn't work.

e.g.

$query = "select * from table where FIND_IN_SET($string, division);
  • 1
    You need quotes around `$string`. But it would be better to use a prepared statement with parameters instead of substituting a variable into the SQL. – Barmar Aug 18 '23 at 21:23
  • @Barmar Just Tried with quotes arounf $string but no luck... – Darshan Inf Aug 18 '23 at 21:25
  • I told you that it's best to use a prepared statement. Don't waste time adding quotes. – Barmar Aug 18 '23 at 21:27
  • But I'm sure ```$query = "select * from table where FIND_IN_SET('$string', division)``` would work. I don't know why it didn't work for you. – Barmar Aug 18 '23 at 21:27
  • @Barmar it works if only one value is there.... e.g. If only Mumbai is there, record fetched but if one than more value with comma, then not fetching... – Darshan Inf Aug 18 '23 at 21:42
  • You have the order of arguments wrong. It should be `FIND_IN_SET(division, '$string')` – Barmar Aug 18 '23 at 21:44
  • 1
    Why not using a `IN` clause? `select * from table where division in ('Mumbai','Solapur')`. Obviously you have to add some logic to dynamically create the query (string or prepared statement), but i think the clause you were looking for is this. – Alberto Fecchi Aug 19 '23 at 01:39

0 Answers0