2012-09-19 45 views
0

我已經使用下面的代碼來爲選中的複選框選擇多個值,以便將其從數據庫表中刪除,但是當我是print_r時,它僅顯示其不顯示id值的鍵。如何獲取php中的多個複選框的值

我使用此代碼在數組中獲取價值: -

<?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"; 
    } 

?> 
+0

試試'var_dump($ _ POST);'。 – 2012-09-19 06:44:25

+0

你不能有id =「複選框[]」,這需要設置爲一個唯一的值。 – jtheman

+0

$ _POST ['checkbox']已經是來自postdata的一個數組,所以你不需要使它變得更安全。 – jtheman

回答

0

$_POST['checkbox']陣列將僅包含選中的複選框:

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

我已經做了foreach使所有的ID INT爲安全目的。

0

你的問題的快速修復方案如下:

替換以下行

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

$array = $_POST['checkbox']; 

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

因爲$ _POST [ '複選框']已經是一個數組

希望這能解決您的問題