3

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.

3
  • Please add which DB product you use (e.g. MySQL) Commented Jun 24, 2016 at 13:40
  • are you not getting desired result as per your given query ? Commented Jun 24, 2016 at 13:41
  • @HamzaZafeer The query should work. I just need some help creating the query from my array Commented Jun 24, 2016 at 13:42

4 Answers 4

4

You can use implode function and IN clause as

$sql="SELECT * FROM v WHERE category IN ('".implode("','", $your_array)."')";
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

I'm using PDO at my DB class. All data is sanitized
FYI I don't know how you santize the data. If you concat a SQL query, with unsantized data, and pass that query to PDO then PDO won't do any sanitizing for you.
The DB class sanitizes the data.
0
$where = 'WHERE category="' . implode('" OR category="', $array) . '"';

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.