Hispanic 100 Hispanic 100 - 2 months ago 9
HTML Question

Constructing mysql select from $_POST array

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().

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

Sanitization is on you :)