1

I am trying to create OR condition dynamically using an array. Given an array, of course names $courses = array('Eng, 'Deu', 'Bio', 'Chemi') I want to have a SQL query that uses the values of the array in its AND clause with OR conditions like:

    SELECT *
        FROM classe
        /* The OR conditions should be created in AND clause using array */
        WHERE class = 'EFG' AND (course = 'Eng' OR course = 'Deu' OR course = 'Bio')

I trying to do it in PHP MySQL.

Any help would be really appreciated.

Thanks in Advance.

2
  • 1
    Maybe and course in( 'Eng', 'Deu', 'Bio')... should be able to generate that pretty easily with implode...or if using PDO this can be much easier. Commented Nov 20, 2018 at 20:04
  • @user3783243 Be very careful using implode on user data as that's an express train to SQL injection bugs. Commented Nov 20, 2018 at 20:42

2 Answers 2

2

Instead of so many OR clauses, you can simply use IN(..):

SELECT *
FROM classe
WHERE class = 'EFG' AND course IN ('Eng' ,'Deu', 'Bio')

In the PHP code, you can use implode() function to convert the array into a comma separated string, and use it in the query string generation.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your reply, with implode I am getting a string like this: "Eng , Deu, Bio" and I want the values like this: " 'Eng' ,'Deu', 'Bio' "
@MusayyabNaveed your problem statement says that you get an array. Please confirm what exactly are you getting ?
yes it in array: $courses = array('Rel-GK1', 'F6', 'Bio', 'Chemi'); $placeholders = implode(', ', $courses);
@MusayyabNaveed check this answer: stackoverflow.com/a/53360802/2469308 You will get the idea on how to do it.
Thank you very much got it :)
|
1

The IN clause will be easier to use than ORs. If you are using PDO you can take advantage of its execute binding and build the placeholders dynamically then just pass your array to it.

$courses = array('Eng', 'Deu', 'Bio', 'Chemi');
$placeholders = rtrim(str_repeat('?, ', count($courses)), ', ');
$query = "select * from table WHERE class = 'EFG' AND course in ({$placeholders})";
$stmt = $pdo->prepare($query);
$stmt->execute($courses);

Demo: https://3v4l.org/jcFSv (PDO bit non functional)

1 Comment

If this is user data you must use prepared statements with placeholder values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.