VishalPethani
VishalPethani

Reputation: 852

How to match array of string in select query?

I am work in php and this is my array

Array ( [0] => Sharp [1] => New [2] => Stress [3] => Bending forward [4] => Headache )

And I Want to retrieve the record which match the array value in tag column

select * 
from table_name 
where tag In(Sharp, New,Stress,Bending forward,Headache);

But above query give the error in php side as like

Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in C:\xampp\htdocs\Demo\abc.php on line 14

And mysql side is

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'forward,Headache) LIMIT 0, 25' at line 1

Thank you in advance

Upvotes: 0

Views: 3045

Answers (1)

devpro
devpro

Reputation: 16117

You are missing quotes for your string value.

This:

SELECT * FROM table_name WHERE tag IN (Sharp,New,Stress,Bending forward,Headache)

Should be:

SELECT * FROM table_name WHERE tag IN ('Sharp','New', 'Stress','Bending forward','Headache')

If you have an array than you can use implode()

$string = implode('","',$yourArray);

$query = 'SELECT * FROM table_name WHERE tag IN ("'.$string.'")';

One more point, as per your code error you are using mysql_* extension which is deprecated and closed in PHP 7. You can use mysqli_* or PDO.

Upvotes: 1

Related Questions