Okay, I'm stuck. After 3 days of stubbornly trying to figure out something that's probably fairly basic, I'm posting this message.
I'm teaching myself how to use PHP to pass HTML form data to a MYSQL db table and return the data to the browser according to the MYSQL query. Here's where I'm stumped: How do I successfully pass multiple values -- either via the CHECKBOX or SELECT (listbox) control -- and return all records matching those values? For example, assume field 1 ("name") lists 10 people and field 2 lists four depts: A, B, C and D (each person is a member of one dept):
"name" | "dept"
Name1 | B
Name2 | C
Name3 | B
Name4 | A
Name5 | A
Name6 | D
Name7 | C
Name8 | B
Name9 | D
Name10 | A
Either a listbox or a checkbox control can provide four selections and allow the user to select one or more departments (dept), submit the selection(s), and view all matching rows. Using the listbox (select) control:
<form method="get" action="page_name.php">
<SELECT name="a[]" multiple="true">
<OPTION value="A">Dept A</OPTION>
<OPTION value="B">Dept B</OPTION>
<OPTION value="C">Dept C</OPTION>
<OPTION value="D">Dept D</OPTION>
</SELECT>
<input type="SUBMIT" value="Submit">
</form>
Or, using the checkbox control:
<form method="get" action="page_name.php">
<INPUT name="myform[]" type="checkbox" value="A">Dept A
<INPUT name="myform[]" type="checkbox" value="B">Dept B
<INPUT name="myform[]" type="checkbox" value="C">Dept C
<INPUT name="myform[]" type="checkbox" value="D">Dept D
<input type="SUBMIT" value="Submit">
</form>
I have no trouble simply echoing each checked value:
foreach($myform as $value) {
echo $value;
}
A MYSQL query must assign a single variable (such as $a) to the entire array of value(s) the user selects. But how do I associate the 'dept' field with the array ($a)? The following query doesn't work (I'm pasting it here just to show where I am in this task):
$a = $_GET['myform'];
$query= "SELECT * FROM mytable WHERE dept='$myform' ";
$result = mysql_query($query);
foreach($a as $value) {
while ($row=mysql_fetch_array($result)) {
echo $row['name'] , " | " , $row['dept'] , "<br>";
}
}
How must I revise this query?