Reputation: 1654
I'm trying to create a SQL Query that gets data from my DB depending on what the array includes.
Example:
My array includes 1, 2, 3
then the query should be SELECT * FROM v WHERE category='1' OR category='2' OR category='3'
.
Does anyone know a way to achieve this?
Any tips are welcome.
UPDATE:
Using MySQL as DB.
Upvotes: 3
Views: 94
Reputation: 1257
You can also try:
$sql = "SELECT * FROM v WHERE ( FIND_IN_SET(".implode("','", $your_array).", category) ) ";
For more info about FIND_IN_SET: http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php
Upvotes: 0
Reputation: 2666
I would take a look at https://stackoverflow.com/a/14767572/755949, which uses placeholders and PDO to add the parameters to your query. Going with Saty's answer you could risk ending up with a SQL injection.
Upvotes: 2
Reputation: 909
$where = 'WHERE category="' . implode('" OR category="', $array) . '"';
Upvotes: 0
Reputation: 22532
You can use implode
function and IN
clause as
$sql="SELECT * FROM v WHERE category IN ('".implode("','", $your_array)."')";
Upvotes: 4