【问题标题】:how to get the value of multiple checkbox in php如何在php中获取多个复选框的值
【发布时间】:2012-09-11 11:09:10
【问题描述】:

我已经使用以下代码为选定的复选框选择多个值以将其从数据库表中删除,但是当我是 print_r 时,它只显示它的键而不显示 id 的值。

我已使用此代码获取数组中的值:-

<?php
echo "Hiiiiiiiiii";
include("conn.php");
$sql="select * from test ";

$res=mysql_query($sql) or die(mysql_error());
?>

<form name="form1" method="POST" action="">
    <table width="578" border="1" align="center" id="menu">
    <tr>
    <th></th>
    <th>id</th>
    <th>Name</th>
    <th>email</th>
    <th>phno</th>
 </tr>

<?php
 while($row=mysql_fetch_array($res))
 {
?>

 <tr>

    <td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
    <td><?php echo $row['id'];?></td>

    <td><?php echo $row['name'];?></td>
    <td><?php echo $row['emailid'];?></td>

    <td><?php echo $row['phno'];?></td>
    <?php
    echo"<td><a href='update.php?id=".$row['id']."'>Update</a></td>";
    ?>
 <?php
  }
 ?>  
 <tr><td><input type="submit" name="delete" value="Delete" id="delete"></td></tr></tr></table>

 <?php
// Check if delete button active, start this
$count = mysql_num_rows($res);
echo "$count";

if(isset($_POST['delete']))
{
    if(count($_POST['checkbox']) !=0)
    {
        $array = array("checkbox" => $_POST['checkbox']);
        print_r($array);
        $ids = implode(',', $array);
        echo "$ids";
        $result = mysql_query("DELETE FROM test WHERE id IN ($ids)") or die(mysql_error());
    }
}
// if successful redirect to delete_multiple.php 
if($result)
    {
     echo "<meta http-equiv=\"refresh\" content=\"0;URL=teach_delinquent.php\">";
     echo "SUCCESS";
    }

 ?>

【问题讨论】:

  • 你不能有 id="checkbox[]" ,这需要设置为一个唯一的值。
  • $_POST['checkbox'] 已经是一个来自 postdata 的数组,所以你不需要把它改成另一个..

标签: php checkbox


【解决方案1】:

$_POST['checkbox'] 数组将只包含复选框:

$ids = array();
foreach($_POST['checkbox'] as $val){
    $ids[] = (int) $val;
}
$ids = implode(',', $ids);

出于安全目的,我已经完成了foreach 以使所有 id 的 INT

【讨论】:

    【解决方案2】:

    您的问题的快速解决方法如下

    替换下一行

    $array = array("checkbox" => $_POST['checkbox']);
    

    $array = $_POST['checkbox'];
    

    $array = array_map('intval',$_POST['checkbox']); // if all values are integer ---for security
    

    因为 $_POST['checkbox'] 已经是一个数组了

    希望这能解决您的问题

    【讨论】:

      【解决方案3】:

      首先你需要计算有多少个复选框

      $counter = sizeof($_POST['checkbox']);
      

      运行一个循环来访问所有这些值

      for($i=0;$i<=$counter;$i++){
          $checkbox_val = $_POST['checkbox'][$i];
      }
      

      这就是你所需要的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-01
        • 2015-02-11
        • 2021-04-26
        • 2014-09-05
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多