I have a simple form containing 5 textareas and a checkbox next to each textarea. The textarea and checkbox values are set to arrays. I then loop through the array for the textarea and insert the records. The textarea values are working fine, but the checkbox values aren’t working as they need to.
The form:
<form action="" method="post" name="form">
<table border="0" align="left" cellpadding="5">
<tr>
<td valign="top">Submission</td>
<td valign="top"><p>Allowed</p></td>
<td valign="top">Comment</td>
</tr>
<tr>
<td width="13%" valign="top">Prescription</td>
<td width="13%" align="center" valign="top"><input name="submission[]" id="submission_1" type="checkbox" value="0" /></td>
<td width="74%" valign="top"><textarea name="comment[]" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td valign="top">Lab Request</td>
<td align="center" valign="top"><input name="submission[]" id="submission_1" type="checkbox" value="1" /></td>
<td valign="top"><textarea name="comment[]" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td valign="top">Generic request</td>
<td align="center" valign="top"><input name="submission[]" id="submission_1" type="checkbox" value="2" /></td>
<td valign="top"><textarea name="comment[]" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td valign="top">Image request</td>
<td align="center" valign="top"><input name="submission[]" id="submission_1" type="checkbox" value="3" /></td>
<td valign="top"><textarea name="comment[]" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td valign="top">Stationery</td>
<td align="center" valign="top"><input name="submission[]" id="submission_1" type="checkbox" value="4" /></td>
<td valign="top"><textarea name="comment[]" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td colspan="3" valign="top"><input type="submit" name="define_submissions" id="submit" value="Add Submissions" /></td>
</tr>
</table>
</form>
The PHP:
$submission = intval($_POST['submission']);
$submission_comment = $_POST['comment'];
if(isset($_POST['define_submissions'])){
for($i=0, $count = count($submission_comment);$i<$count;$i++) {
$comment = $submission_comment[$i];
$query_level_1 =
sprintf("INSERT INTO submission (
submission_pk,
pathway_fk,
submission_allowed,
comment
) VALUES (
'',
'$pathway',
'%s',
'$comment')", $submission === $i ? 'y' : 'n');
$result_level_1 = mysql_query($query_level_1, $connection) or die(mysql_error());
}
AFAIK, checkbox value are not sent to server, when not checked. So, you need to, first, check if it is exists / defined.
To make it easier, just add key value to your check box:
And then, define the $submission:
Inside for loop:
And change your query line into: