Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use where clause by sequence of ids

I have a sequence of ids that merged by a comma :

$ids = '1,2,3,4,5,6,7,8,9,10' ;
select * from ads WHERE id = $ids ...

now how can I get content of ads table by these ids ?

like image 588
S.M_Emamian Avatar asked Jan 18 '26 20:01

S.M_Emamian


2 Answers

You are using PHP. You can build the SQL like this:

$ids = '1,2,3,4,5,6,7,8,9,10';
$sql = 'SELECT * FROM ads WHERE id IN ('.$ids.')';
//execute the query (don't use mysql_* function ;) )

Since MySQL 5.6 you can use FIND_IN_SET() too:

$ids = '1,2,3,4,5,6,7,8,9,10';
$sql = "SELECT * FROM ads WHERE FIND_IN_SET(id, '".$ids."')";
//execute the query (don't use mysql_* function ;) )
like image 85
Sebastian Brosch Avatar answered Jan 20 '26 14:01

Sebastian Brosch


Use IN operator

Try this:

SELECT * 
FROM ads 
WHERE id IN ($ids);
like image 38
Saharsh Shah Avatar answered Jan 20 '26 14:01

Saharsh Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!