首页 > 解决方案 > 在 PHP 中收集多个复选框的值(2 以相同的形式提交?)

问题描述

我有两个以相同的形式提交。一个用于过滤 mySQL 数据库并生成复选框列表(工作正常),另一个用于使用 PHP 显示所选项目的值(不行)。稍后,我将存储这些值来构建一个 sql 查询。请访问https://wintoweb.com/sandbox/question.php

我已经尝试了你能想象到的一切。快疯了...

从 [Show selected] 按钮调用的 PHP 函数:

<?php      
function getNames() {
    //echo 'GOT IT !';              
    if(isset($_GET['choices[]'])){
        if(!empty($_GET['choices'])){
            foreach($_GET['choices'] as $selected){
                echo $selected."</br>";
            }
        }
    }
}
?>

[显示所选] 按钮的代码:

预期:实际输出下方的选定值列表:没有选定值列表。PHP 函数 getNames() 永远不会被遍历。

标签: phpformscheckbox

解决方案


我简化了你的表格。

<form name="dig" action="#" method="get">
<input type="search" name="l_name" value="Author's name (whole or part)" style="width:200px;" onfocus="this.value=''" onblur="(this.value=='')? this.value='Author's name (whole or part)':this.value;" />
<input type="submit" name="search" value="Search"> 
<input type="submit" name="display_all" value="Show selected">
<br /><br />
<table style="width:400px">
    <tr>
        <td width="100%"><input type="checkbox" name="choices[]" value="ABÉLARD, Pierre et HÉLOÏSE" onclick="">ABÉLARD, Pierre et HÉLOÏSE</td>  
    </tr>
    <tr>
        <td width="100%"><input type="checkbox" name="choices[]" value="ABOUT, Edmond" onclick="">ABOUT, Edmond</td>  
    </tr>
    <tr>
        <td width="100%"><input type="checkbox" name="choices[]" value="ABRANTÈS, Laure Junot" onclick="">ABRANTÈS, Laure Junot</td>  
    </tr>
</table>
</form>

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);

if(isset($_GET['search'])){
    echo 'Search</br>';
} elseif(isset($_GET['display_all'])) {
    echo getNames();
}

function getNames() {
    $rets = '';
    if(isset($_GET['choices']) and !empty($_GET['choices'])){
      foreach($_GET['choices'] as $selected){
        $rets .= $selected.'</br>';
      }
    }
    return $rets;
}

推荐阅读