两个复选框以相同的形式相互冲突

时间:2018-11-06 01:26:50

标签: php

我有两个包装在表单中的复选框 $ multID $ catID ,每当我选择这两个复选框时,它们都无法正常工作,我需要对它们进行均等检查对于其他工作,即我需要分别检查3-2的 $ multID $ catID 的2-2或1-1或3-3复选框或1-3框将无法使用。我的意思是这----->如果我从$ multID中选择两个项目,然后从$ catID中选择一个项目,它将只插入一个$ multiD bcos项,而我只选择了$ catID中的一个到数据库中,但是如果我选择它们相等,即$ multID的两个和$ catID的两个,那么它将正常工作......请帮助解决此问题

我用这个

$stmt = $db->prepare('INSERT INTO blog_post_cats (postID,catID,nickID,avaID,multiID)VALUES(:postID,:catID,:multiID)');
foreach ($_POST['catID'] AS $i => $catID) {
    $multiID = $_POST['multiID'][$i];
    $stmt->execute(array(
                       ':postID' => $postID,
            ':catID' => $catID,

            ':multiID' => $multiID

                       ));
}

我的表单看起来像这样

<form action='' enctype='multipart/form-data' method='post'>

<p><label>Title</label><br />
<input type='text' name='postTitle' value='<?php if(isset($error)){ echo $_POST['postTitle'];}?>'></p>
<br/><br/>
 <?php    
$checked = null;
$stmt3 = $db->query('SELECT multiID, multiTitle FROM multi_image ORDER BY multiID');
while($row3 = $stmt3->fetch()){
    if(isset($_POST['multiID'])){
        if(in_array($row3['multiID'], $_POST['multiID'])){
           $checked="checked='checked'";
        }else{
           $checked = null;
        }
    }

    echo "<input type='checkbox' name='multiID[]' value='".$row3['multiID']."' $checked> <img width='40px' src='upload/blog/".$row3['multiTitle']."'/><br />";
}
?>

<p><label>Content</label><br />
<textarea name='postCont' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postCont'];}?></textarea></p>

<fieldset>
<legend>Categories</legend>

<?php    
$checked = null;

$stmt2 = $db->query('SELECT catID, catTitle FROM blog_cats ORDER BY catTitle');
while($row2 = $stmt2->fetch()){
    if(isset($_POST['catID'])){
        if(in_array($row2['catID'], $_POST['catID'])){
           $checked="checked='checked'";
        }else{
           $checked = null;
        }
    }

    echo "<input type='checkbox' name='catID[]' value='".$row2['catID']."' $checked> ".$row2['catTitle']."<br />";
}
?>
</fieldset>

<p><input type='submit' name='submit' value='Submit'></p>

</form>

1 个答案:

答案 0 :(得分:0)

您需要遍历一个数组,然后使用索引访问另一个数组的相应元素。

$stmt = $db->prepare('INSERT INTO blog (postID,catID,multiID)VALUES(:postID,:catID,:multiID)');
foreach ($_POST['catID'] AS $i => $catID) {
    $multiID = $_POST['multiID'][$i];
    $stmt->execute(array(
                       ':postID' => $postID,
                       ':catID' => $catID,
                       ':multiID' => $multiID
                       ));
}

请注意,您只需要准备一次语句,而不必每次遍历循环。