6

This is the $_POST array from my form.

Array ( [prescribedid] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 13 ) 

I want to create a select for any of items in the Array. I have written this, which produces the proper SELECT, but the if() to eliminate a trailing OR makes it clunky.

$query = "SELECT * "; $query .= "FROM prescribed WHERE "; for($i=0; $i<count($_POST["prescribedid"]); $i++) { $query .= "prescribedid={$_POST['prescribedid'][$i]} "; if($i < (count($_POST["prescribedid"])-1)) { $query .= "OR "; } } 

It produces this:

SELECT * FROM prescribed WHERE prescribedid=1 OR prescribedid=2 OR prescribedid=3 OR prescribedid=9 OR prescribedid=13 

Is there another way to group the SELECTS or write the FOR() to make it cleaner, i.e. without the last IF().

2
  • 3
    Tip: You can use IN in order to avoid multiple OR clauses. ...WHERE prescribedid IN (1,2,3,9,13).... Commented Aug 17, 2016 at 7:16
  • 2
    Tip: You need to use PDO or vaidate input. This code can be used for SQL injection. Commented Aug 17, 2016 at 7:18

4 Answers 4

8
$values=implode(",",$_POST["prescribedid"]); $query = "SELECT * FROM prescribed WHERE prescribedid IN ($values)"; 

Sanitization is on you :)

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

Comments

4

Hi You can Use In condition. use imploade function to find comma seoarated values

$data = array('prescribedid'=>array(1,2,3,9,14)); $query = 'SELECT * FROM prescribed WHERE prescribedid IN ('; $query .= implode(',',$data['prescribedid']).')'; echo $query ; 

Output

SELECT * FROM prescribed WHERE prescribedid IN (1,2,3,9,14) 

1 Comment

You don't need the string concatenation (and it may cause some confusion, especially in this layout.)
4

Use MySQL IN clause

$ids = implode(",",$_POST["prescribedid"]); $query = "SELECT * FROM prescribed WHERE prescribedid IN ($ids)"; 

Comments

2

You can simply use IN clause here.

Refer to MySQL IN clause

$query = "SELECT * FROM prescribed WHERE prescribedid IN ".implode(',', $_POST["prescribedid"]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.