tags:

views:

74

answers:

4

Hi, I've got a code that echos out every row of the database with a checkbox next to it.

$result = mysqli_query($database, "SELECT * FROM $imei_to_look_for" );
while ( $row = mysqli_fetch_array($result) ) {

echo htmlspecialchars($imei_to_look_for).
"<input type='checkbox' value='$row[event_number]' name='todelete[]' />";

and another, that should loop throught all checked checkboxes.

foreach ( $_POST['todelete'] as $delete_id ) { ...

yet it gives an "Invalid argument supplied for foreach()" error.

Any suggestions? Thanks!

+1  A: 

That error is typically caused by passing something other than an array (or other iterable object) into foreach.

Have you done a var_dump or print_r on $_POST to ensure that todelete[] is actually coming through as an array?

Neil Aitken
@Neil: I even did the formatting and did not see that (*how sad*) thanks for pointing that out.
Anthony Forloney
np, I totally missed it the first time as well :)
Neil Aitken
well, it certainly appears to be not an array... what now?
@user Strange, could you please post the form HTML into your question so that we can see what's up with it.Also what does the var_dump out actually show?
Neil Aitken
+3  A: 

Replace

foreach ( $_POST['todelete'] as $delete_id ) { ...

with

if( is_array( $_POST['todelete'] ) ) {
    foreach ( $_POST['todelete'] as $delete_id ) { ...
} else {
    echo "$_POST['todelete'] is not an array";
}

This will prevent your code erroring when you haven't received an array, and help you debug the POST data (which is apparently not what you're expecting).

Andy
well, it certainly appears to be not an array... what now?
@andy: Even better, write the foreach once, and `if (!isarray($x)) $x = array($x);`. That way you don't have to duplicate the logic inside the `foreach`.
Billy ONeal
+1  A: 

Have you tried moving the name='todelete[]' to the select tag? It seems you have it declared in the wrong place in your select/options html.

An example here: http://www.onlinetools.org/tricks/using_multiple_select.php

zaf
the [] notation can be used on most input elements, I wasn't certain so I checked it here http://www.johnrockefeller.net/html-input-forms-sending-in-an-array-in-php/
Neil Aitken
>>> Have you tried moving the name='todelete[]' to the select tag? It seems you have it declared in the wrong place in your select/options html.No, I took that line from another script that works fine.
A: 

GOT IT! I just forgot that line on top! :)))

  <form id="form1" name="form1" method="post" action="">
!!!!!!!!!!!!!!!
zaf