Forum Moderators: coopster

Message Too Old, No Replies

determining which elements were checked on a previous page....

         

dmmh

10:11 pm on Feb 23, 2005 (gmt 0)

10+ Year Member



I have a database editing page, where I can add movie details and such. each movie can have multiple genres, so I store these in a separate table. sofar so good. I have made on the editing page checkboxes next to the genres currenctly associated with the movie, if I check those, it indicates I want to delete them.

now, the problem is, I can easily determine how many checkboxes were checked ,with count(), but I dont know a way to determine which were checked. This is a problem, because I cannot verify this way what to delete, as the $_POST['genre'] array will vary in lenght from the checkboxes array, say $_POST['del_genre'].

An example: I have 4 genres, so count($_POST['genre']) == 4. Two of those, the first and the third, I want to have deleted. I first purge all the genres from the database btw, then insert the new values. So, count($_POST['del_genre']) == 2.

because the first index of the second array will just be 0 and the second 1, i could perhaps delete the first and second item from the database (or not re-insert it if you please), but I can not delete the third, because I dont know a way to determine which checkbox was checked.

hope I am making myself clear. any pointers?

ironik

11:38 pm on Feb 23, 2005 (gmt 0)

10+ Year Member



This is the method I use (where the attribute value is the primary key value of the database row):

<input type="checkbox" name="delete[]" value="1">
<input type="checkbox" name="delete[]" value="2">
<input type="checkbox" name="delete[]" value="3">

The $_POST array data is only populated if the checkbox is ticked, so if checkbox 1 and 3 were ticked you would get the array values like this:

printr($_POST['delete']);
/* which outputs:
array {
[0] => 1,
[2] => 3,
}*/

You can process this array into your SQL statement:

$SQL = "DELETE FROM table WHERE ";
foreach ($_POST['delete'] as $key=>$dbKey)
{
$SQL .= "primary_key='" . $dbKey . "' AND ";
}
// Trim the last AND off
$SQL = substr($SQL, 0, -5);

Hope this gets you headed in the right direction.

dmmh

6:39 am on Feb 24, 2005 (gmt 0)

10+ Year Member



mmmm, I always thought it would be like:

printr($_POST['delete']);
/* which outputs:
array {
[0] => 1,
[1] => 3,
}*/

guess I had an error in my thinking then. If its like this, there's no problem at all, thanks

coopster

12:16 pm on Feb 24, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



No, you are correct there dmmh, the array indexes do not skip, they are incremental.

Why not make the "key" the checkbox item value? Use a <label> to identify the "human-readable" part.

dmmh

8:13 pm on Feb 25, 2005 (gmt 0)

10+ Year Member



stupid, I actually have it set up like that and it does work ok. Just never tested it as I thought it wouldnt work lol. thx guys