2

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.

alex.b
  • 4,497
  • 1
  • 30
  • 51
Chris
  • 1,443
  • 4
  • 16
  • 46

4 Answers4

4

You can use implode function and IN clause as

$sql="SELECT * FROM v WHERE category IN ('".implode("','", $your_array)."')";
Saty
  • 22,213
  • 7
  • 30
  • 49
2

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.

Community
  • 1
  • 1
Rob
  • 2,346
  • 1
  • 19
  • 40
0
$where = 'WHERE category="' . implode('" OR category="', $array) . '"';
newage
  • 841
  • 7
  • 18
0

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

HarisH Sharma
  • 1,009
  • 1
  • 11
  • 34