2014-05-20 63 views
-1
<?php 

// $groups is fetch_array from mysql 
foreach($groups as $group) { 
    if ($group['delete_user'] === 'Y') { 
     $checked = "checked=\"checked\"; 
    } 
    else { 
     $checked = ''; 
    } 
?> 
    <input type = "checkbox" name="delete_user[<?php echo $group['id']; ?>]" <?php echo $checked; ?>> 
<?php 

} 
?> 

將輸出:PHP獲取複選框價值/未選中

<form action="test.php" method="post"> 
    <input type="checkbox" name="delete_user[1]"> 
    <input type="checkbox" name="delete_user[2]"> 
    <input type="checkbox" name="delete_user[3]"> 
    <input type="checkbox" name="delete_user[4]" checked="checked"> 
    <input type="submit" name="save_action" value="Save"> 
</form> 

當我檢查輸入通緝,那麼這將處理輸入。

<?php 
if(isset($_POST['save_action']) { 
    if (empty($_POST['delete_user'])) { 
     $_POST['delete_user'] = array(); 
    } 
    foreach($_POST['delete_user'] as $del) { 
     is_checked($del); //@todo 
    } 
} 
?> 

我在查找是否檢查複選框並返回適當的值(Y或N)。在這一點上,我爲此目的聲明瞭is_checked()函數。

+0

$ _POST ['delete_user']將只包含那些已被選中的項目。 –

+0

那麼,按照HTML表單的工作原理,它只會檢查被檢查的複選框的POST值。 – mituw16

回答

0

我會做這樣的:

<form action="test.php" method="post"> 
    <input type="checkbox" name="delete_user[]" value="1"> 
    <input type="checkbox" name="delete_user[]" value="2"> 
    <input type="checkbox" name="delete_user[]" value="3"> 
    <input type="checkbox" name="delete_user[]" value="4" checked="checked"> 
    <input type="submit" name="save_action" value="Save"> 
</form> 

現在PHP可以循環在$ _ POST [「DELETE_USER」],它會包含所選項目的值。

foreach($_POST['delete_user'] as $item) 
{ 
    // code to delete $item 
} 
0

如前所述,只有選中的複選框將被設置 所以,你要麼必須走索引作爲ID或VAL添加到每個輸入元素的意見。 後者很可能會更清潔(在我看來)

<?php 
// $groups is fetch_array from mysql 
foreach($groups as $group) { 
    if ($group['delete_user'] === 'Y') { 
     $checked = "checked=\"checked\"; 
    } 
    else { 
     $checked = ''; 
    } 
?> 
    <input type = "checkbox" name="delete_user[]" <?php echo $checked; ?> value="<?php echo $group['id'];?>"> 
<?php 
} 
?> 

並做了與輸入代碼:

<?php 
if(isset($_POST['save_action']) { 
    if (empty($_POST['delete_user'])) { 
     $_POST['delete_user'] = array(); 
    } 
    foreach($_POST['delete_user'] as $del) { 
     // do something with $del - the id 
    } 
} 
?> 
0

使用複選框名稱只是作爲一個數組,然後給ID爲值。請參閱下面的代碼。

<?php 
// $groups is fetch_array from mysql 
foreach($groups as $group) { 
if ($group['delete_user'] === 'Y') { 
    $checked = "checked=\"checked\"; 
} 
else { 
    $checked = ''; 
} 
?> 
<input type = "checkbox" name="delete_user[]" value="<?php echo $group['id']; ?>" <?php echo $checked; ?>> 
<?php 

} 
?> 

然後在操作頁面將此代碼

<?php 
     foreach($_POST['delete_user'] as $del) { 
     is_checked($del); //@todo 
    } 
} 
?> 

這將正常工作。