TopTomato
TopTomato

Reputation: 585

PHP - trying to create an array of checkboxes,

I'm trying to create an Array from multiple checkboxes that are created via a while loop. the check boxes are named 'to_delete[1]', 'to_delete[2]', etc. etc. the array statements i've tried are these:

$toDelete = array($_POST['to_delete']);
$toDelete = array($_POST['to_delete'][]);

to veryify there is an array, i go to print but find it is empty print_r($toDelete). What am i doing wrong? the code is below. Yes, i'm doing this procedurally, and then will re-write as OOP. big thanks for any help on this!,

$showQ = "SELECT * FROM urls";
$result = mysql_query($showQ);
$numRows = mysql_num_rows($result);
$row = mysql_fetch_array($result);

if(!$result) {
    mysql_error();
   } else {
  echo "<form action='".$_SERVER["PHP_SELF"]."' method='post'>";
  $i=0;
  while($row = mysql_fetch_array($result)) {
    echo "<input type='text' class='manId' name='manId[]' value=" . $row['id'] . " />";
echo "<input type='text' class='url' name='url[]' value=" . $row['url'] . " />";
echo "<input type='checkbox' name='to_delete[" .$i. "]' /><br/>\n";
$i++;
}
echo "<input type='submit' value='delete' name='submit'  />";
echo "</form>";
}
$toDelete = array($_POST['to_delete[]']);
print_r($toDelete);

Ultimately, i want to traverse the array, see which ones are checked and then delete the corresponding row from the table.

Upvotes: 0

Views: 169

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

You don't want to create an array with the array() call, but rather to access one. $_POST will receive input names ending with [] as arrays, so the corresponding array keys in $_POST will already be arrays. The way you've written your code, you are assigning a one-element array containing a sub-array from $_POST. Instead, try the following:

// Test if $_POST['to_delete'] is set and non-empty
// If it's empty, create an empty array, otherwise assign it to $toDelete
$toDelete = empty($_POST['to_delete']) ? array() : $_POST['to_delete'];
print_$($toDelete);

Upvotes: 2

Related Questions