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,547
  • 1
  • 31
  • 52
Chris
  • 1,574
  • 4
  • 16
  • 49

4 Answers4

4

You can use implode function and IN clause as

$sql="SELECT * FROM v WHERE category IN ('".implode("','", $your_array)."')";
Saty
  • 22,443
  • 7
  • 33
  • 51
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,466
  • 3
  • 22
  • 40
0
$where = 'WHERE category="' . implode('" OR category="', $array) . '"';
newage
  • 899
  • 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,101
  • 1
  • 11
  • 38