具有单独复选框值的多个插入

时间:2012-12-19 03:46:42

标签: php mysql

我有一个包含5个textareas的简单表单,每个textarea旁边都有一个复选框。 textarea和checkbox值设置为数组。然后我循环遍历textarea的数组并插入记录。 textarea值工作正常,但复选框值无法正常工作。

表格:

<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>

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());
}

1 个答案:

答案 0 :(得分:0)

未选中时,

AFAIK,复选框值不会发送到服务器。因此,您需要首先检查它是否存在/定义。

为方便起见,只需在复选框中添加键值:

<input name="submission[0]" id="submission_1" type="checkbox" value="0" />
<input name="submission[3]" id="submission_1" type="checkbox" value="3" />

然后,定义$ submission:

$submissions = $_POST['submission'];

Inside for循环:

$submission = isset($submissions[$i]) ? 'n' : 'y';

将您的查询行更改为:

'$comment')", $submission);