在下一页显示动态复选框的值.并插入这样的值


displaying value of dynamic checkbox in next page . and inserting such value

我创建了一个动态复选框,但未能在另一个页面上显示其值。我所做的工作如下:

index.php

<form method="post" action="print.php">
    <?php 
    $host="localhost";
    $username="root";
    $password="";
    $database="checkbox";
    mysql_connect($host,$username,$password);
    mysql_select_db("$database");
    //Create the query
    $sql = "select test, rate FROM lab";
    $result = mysql_query($sql) or die(mysql_error());
    while($row = mysql_fetch_assoc($result)) {
        echo <<<EOL
        <input type="checkbox" name="name[]"value="$row['test']}/{$row['rate']}"/>          
        {$row['test']}-{$row['rate']}<br />
        EOL;
    }
    ?>
    <br>
    <input type="submit" name="submit" value="Add" />
</form>

我正试图在一个名为print.php的secon页面上显示该值:

<?php
print $_POST['name'];
?>

您需要使用print_r函数来显示数组中的所有值。像

print_r($_POST['name']);

查看代码中发生了什么:-您正在数组中命名您的复选框。因此,当您在php中获得提交时,您将收到一个名称为:-name[]的数组因此$_POST['name']将在php中返回一个数组。当您使用print方法时,它只能打印变量值。它无法打印数组或对象。如果使用print/echo方法打印数组/对象,它只会打印它们的类型。因此,要打印数组,您可以使用print_r()方法,或者使用var_dump()检查变量中的内容。您可以通过任何循环按自己喜欢的方式访问数组。有关print-r和var_dump的更多信息,请访问手动链接[php.net手册][1]http://www.php.net/manual/en/function.var-dump.php

您需要一些方法来确定选中了哪个复选框。您有两个选项对变量使用和索引,并将其作为索引或从值中标识它。

在这里,我添加了$rowNum作为name的索引。

$rowNum=0;
while($row = mysql_fetch_assoc($result)) {
  echo <<<EOL
  <input type="checkbox" name="name[$rowNum]"value="$row['test']}/{$row['rate']}"/>          
      {$row['test']}-{$row['rate']}<br />
EOL;
$rowNum++;
}

在这里,如果你只选中第一个和第三个复选框,在PHP你会得到

$_POST['name'] = Array
(
    [0] => test0/rate0
    [2] => test2/rate2
)

如果您没有像在代码中那样使用$rowNum,并且选择了与上面相同的选项,那么您将获得以下输出。

$_POST['name'] = Array
(
    [0] => test0/rate0
    [1] => test2/rate2
)

你可以在print.php 上使用这样的阵列

if (is_array($_POST['name'])){
    foreach($_POST['name'] as $key=>$name){
        echo $key, '=>', $name,'<br/>';
        //Here $key is the array index and $name is the value of the checkbox
    }
}