vendredi 25 septembre 2015

combined arrays in foreach loop with if statement and query partially failing

I have a page with a simple list of items pulled from a mysql table. Each of the items falls into one of two categories. In the database I have "Status" column. Items are either in Status 1 or Status 0. One for each group.

On each of the items on the page I've added a checkbox with the primary key for its row in the table. Within each item in a given category on the page. I also have a hidden field with the $_POST['Status'] set to correspond to which group it's currently in. With the code below, I have the Status array and check_list (which is the primary key) merging correctly into key and value pairs.

I want people to be able to check the checkboxes in both groups and have the status change with one button click essentially moving an item from one group to the other. I have three items that I've been bouncing around between the two groups.

Everything in Group 1 works fine. I can move one item at a time until its empty, two items at a time, and all three at once with no issue. Group 0 is not working. I can move three items at a time with no issue, I can move two items simultaneously with no problem, but I can only move one item one at a time once. The second time around, nothing budges. If I select both of the remaining items in that group, only the first one moves.

It's very strange behavior. I think it has something to do with the way the if statements are executed in the foreach loop, but I'm not sure how to solve it.

function combine_arr($a, $b) { 
    $acount = count($a); 
    $bcount = count($b); 
    $size = ($acount > $bcount) ? $bcount : $acount; 
    $a = array_slice($a, 0, $size); 
    $b = array_slice($b, 0, $size); 
    return array_combine($a, $b); 
} 
if(isset($_POST['Move'])) {
    if(!empty($_POST['check_list'])) {
        $combined = combine_arr($_POST['check_list'], $_POST['Status']);
        foreach ($combined as $key => $value) {
            if($value == 1) {
                mysqli_query($con, "UPDATE items SET Status=0 WHERE ID=$key");
            }
            if($value == 0) {
                mysqli_query($con, "UPDATE items SET Status=1 WHERE ID=$key");
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire