保留选中While内的复选框

时间:2015-08-10 17:31:04

标签: php

此代码在我提交表单之后,而不是在提交后保留我检查的所有内容。

我只是想在提交唯一的复选框后检查我检查。

我该怎么办?

 <input  type="checkbox" title ="<?php echo $sym ?>"<?php if(isset($_POST['poscon'])) echo "checked='checked'"; ?> name="poscon[]" value ="<?php echo $pc?>"><?php echo $pc?>

2 个答案:

答案 0 :(得分:1)

$ _ POST ['poscon']是一个数组。运行我的脚本,看看它是如何工作的。

<?php
/**
 * File test.php
 */


// Store checked Values in Array $arrChecked
$arrChecked=array();
if(isset($_POST) && $_POST['poscon']) {

    // Debug: Show all POST Vars
    echo "<pre>"; print_r($_POST); echo "</pre>";


    foreach($_POST['poscon'] AS $checkboxValue) {
        // fill array with checked values
        // e.g. arrChecked['foo'] = true;       
        $arrChecked[$checkboxValue] = true;
    }
}

/** 
 * Note for HTML-Block:
 * shorthand php if/else used
 * http://stackoverflow.com/questions/4567292/overview-of-php-shorthand
 */
?>

<form action="test.php" method="post">
    <input type="checkbox" name="poscon[]" value="foo" <?php echo (isset($arrChecked) && $arrChecked['foo'] ? 'checked="checked"' : '');?>> foo

    <input type="checkbox" name="poscon[]" value="bar" <?php echo (isset($arrChecked) && $arrChecked['bar'] ? 'checked="checked"' : '');?>> bar

    <input type="submit" value="go">
</form>

答案 1 :(得分:1)

参考in_array

<?php
if(isset($_GET["poscon"])) { 

    $_SESSION["poscon"] = $_GET["poscon"]; 
    $dr=$_SESSION['poscon']; 

    if(isset($_POST['submit'])) { 
        if(!empty($_GET['poscon'])) 
            $_SESSION['poscon'] = $_POST['poscon']; 
        $part=$_GET["poscon"]; 
    }

    $poscon=mysqli_real_escape_string($link,$_GET['poscon']); 

    $p = mysqli_query($link,"select distinct PossibleCondition,Symptoms from healthguide where Subpart like '%$poscon%' and PossibleCondition REGEXP '^[N-Z].*$' Order by PossibleCondition "); 

    while($r=mysqli_fetch_array($p)) { 
        $pc=$r["PossibleCondition"]; 
        $sym=$r["Symptoms"]; 

        if(isset($_POST) && isset($_POST['poscon']) && in_array($pc,$_POST['poscon']))
            $strIsChecked='checked="checked"';
        else
            $strIsChecked=null;

        echo '<tr>';    
        echo '<td><input type="checkbox" '.$strIsChecked.' title ="'.$sym.'" name="poscon[]" value ="'.$pc.'"></td>';
        echo '<td>'.$pc.'</td>';
        echo '</tr>';   

    } 

} 
?>