1

I am writing a PHP/MySQL application that maintains a masterlist of user preferences and I've gotten myself stuck trying to remove items from that list. Currently the application generates a list of items and marks a checkbox next to the ones a user has previously selected, the user can then change their selections (either adding or removing checkmarks) and resubmit. The form only submits supplyid's for items the user has checked.

I have the list sorted so that unmarked selections are shown first and I've got the code to insert/update items in the database working, but I'm having problems figuring out how to delete the items the user has unchecked (and which now do not return supplyid's).

At this point, I've written a MySQL query to return only results that were previously included on the list (as those are the only ones which could need to be removed.) What I need are the items in the array returned by the query that do not match any $_POST results. I've been successfully comparing the array to the $_POST results of items previously included, but I can see my logic is wrong in the part where I'm trying to get back the results which don't match. While I'm able to view which items match, I'm not sure how to eliminate them as possibilities. Am I going about this in the wrong way entirely?

$iduser = $_SESSION["iduser"];
$possibleresults = $_POST["possibleresults"];
$sql_onlist = "select supply.idsupply from supply, kit
                    where supply.class = 'basic'
                      and kit.iduser = '".$iduser."'
                      and supply.idsupply = kit.idsupply";

$possible_delete = $connection->query($sql_onlist);

//for each record we know is already in the database, check to make sure it has been checked, otherwise delete
for ($i=0; $i<$possibleresults; $i++) {
$count = 0;
$item_delete = $possible_delete->fetch_assoc();
if ($_POST['item_'.$i.'']) {
    $idsupply = $connection->real_escape_string($_POST['item_'.$i.'']);
//if there is a match, increase the counter
if ($idsupply == $item_delete["idsupply"]) {
    $count++;
    //this does successfully return a count = 1 - idsupply = number for all rows which should have matches
        echo "count = ". $count . " - idsupply = " . $idsupply;
}           
    //this statement doesn't work because it doesn't know which idsupply
    if ($count < 1) {
        $idsupply = $item_delete["idsupply"];
        $sql_delete = "delete from kit 
                  where idsupply = '".$idsupply."'
                  and iduser =  '".$iduser."'";
    $result_delete = $connection->query($sql_delete);   
    }
}
2
  • Have you tried just reloading the list with the same params that you used to load it the first time (when you showed the checkboxes) and comparing against that?
    – JohnP
    May 10, 2011 at 4:53
  • Even easier would be to delete all options, and just readd the ones that are checked. That's essentially what you're trying to do
    – JohnP
    May 10, 2011 at 4:53

3 Answers 3

2

There are a couple different solutions to this problem; here's a few strategies I've used before.

-- Delete all the entries every time you update a user's preferences
Not terribly efficient, but it's easy to implement. Every time they save their preferences, first set all the values in the database to whatever the 'unchecked' value is. Then, save their preferences as normal.

-- Give unchecked boxes a value
If you put a hidden input element right before a checkbox and give it the same name as the checkbox, the hidden element will submit its value whenever the checkbox is not checked. E.g.,

<input type='hidden' name='box1' value='off' />
<input type='checkbox' name='box1' value='on' />

This will let you know which IDs to unset in the database.

There may be a more database-oriented solution as well, but I'd have to know more about your structure to suggest anything.

3
  • Gah, beaten by 20 seconds with the exact same answer. +1 to you sir
    – Phil
    May 10, 2011 at 4:57
  • +1 didn't know about the hidden field trick. I've noticed cake generating the fields, but never connected the two facts
    – JohnP
    May 10, 2011 at 4:58
  • Thanks! That is a neat trick (which I'll try to implement when it's not 2am...) In the meantime, the delete/re-add works, which is a beautiful thing!
    – Becca
    May 10, 2011 at 6:01
0

Holy moly, what a tangled mess... kinda painted yourself into a corner eh? No worries it happens to all of us. :)

So I think that once you have a truly working algorithm the code just kinda comes together around it. So lets analyze your problem:

  • Your main objective is to store a users settings.

  • You are using a form and checkboxes to both display the current settings and to allow the user to change their current settings. This is graceful enough.

  • Generate a list of the users POSTed settings (aka get the new settings from the POST array) and store those results in a dedicated data container like an array or a linked list.

  • Once you have a list of new settings, you need to use that list as a map to set/unset various fields within a database table.

  • Get a list of ALL of the users saved settings from the database storing that in a different data container

  • Do a case by case comparison, seeing if the variables match, record the results in yet another data container, or do an immediate write to the database.

  • Present the user with a human readable result of their operation.

    NOTE: Incidentally, you probably already know this, but if you use isset($_POST['mychkbox1']) and it returns a positive value, then that checkbox was checked. If isset() returns false, the checkbox was not set, or does not exist. Like I said you probably already knew that, but I figured I toss it in there.

    Good luck

h

2
  • In the light of day, your answer walked me through what I needed to do without deleting all my records (which didn't work out in this case because I had fields saved into the table from elsewhere and unless I passed them as hidden inputs they were being lost) or restructuring my table entirely (although I admit it was poor form design that "painted me into the corner" to begin with!) Thanks so much!
    – Becca
    May 10, 2011 at 12:58
  • @Becca, glad I could help :) I have discovered that one of the best rules to follow when programming is "Occam's Razor" -- the concept that "the simplest solution is most often the correct solution." Sounds like you are out of the corner and back on the road, good luck! May 10, 2011 at 18:02
0

I didn't quite understand your code, but I think you need something like this

$to_keep = array();
for ( $i=1 ; $i < 10 ; $i++ ) {
    // Add ids of elements we want to save
    $to_keep[] = $i;
}
if ($to_keep) {
    mysql_query("DELETE FROM table WHERE id NOT IN (". implode(',', $to_delete) . ")");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.