I am trying to build a dynamic query based on user choices from a checkbox form. The user can select up to 12 boxes.
My problem. How can I build a query based on how many selections they make.
Basic query says:
$sql = 'SELECT number, name, notes, retail FROM attachment_options WHERE attachment_id ='.$attn[0];
My array values are $attn[X] and I can echo all of them chosen.
How can i build the $sql to add AND '.$attn[1].' AND '.$attn[2].'....etc for however many the user chooses? I know there must be way to incorporate a for() or foreach() statement into the query but I have not been able to find the correct syntax for such a situation.
I know I could do a series of if statements based on the count($attn) but there must be a more efficient way. Here is one thing i have tried that must be close:
$countatt=count($attn);
if ($countatt==1)
$sql = 'SELECT number, name, notes, retail FROM attachment_options WHERE attachment_id ='.$attn[0];
elseif($countatt>1)
{
for ($i=1;$i<$countatt;$i++)
{
$value=$attn[$i];
$string="AND '.$value.'";
}
$sql = 'SELECT number, name, notes, retail FROM attachment_options WHERE attachment_id ='.$attn[0].$string;
}
echo "$sql<br>";
$result = mysql_query($sql) or die ("I cannot do query because" . mysql_error());
When I try this code, $sql will not echo(when count is >1) and die error says query was empty.
I know the PHP geniuses here know how to do this. I would appreciate any help here. Thanks.