INSERT/DELETE records using checkboxes

I have a form with a bunch of checkboxes (which are generated from a 2 column table.When the form is first loaded, ALL the amenities (Ocean View, Parking, New Furnishings… are simple checkboxes. Only the amenities chosen for that property are already checked (any amenity with the same propertyID). I’m trying to make it so that you can simply add an amenity to a property by checking and on the flip side you can remove an amenity from a property by unchecking it. I dont know how to do this. Heres how I show ALL the amenities

            $stmt = $conn->query('SELECT name FROM amenities');
                while ($row = $stmt->fetch())
                {
                    echo '<div class="checkbox col-sm-4">';
                    echo '<label>';
                    echo "<input type='checkbox' name='Amenities[]' value='".$row['name']."' multiple>";
                    echo '<span class="cr"><i class="cr-icon fa fa-check"></i></span>';
                    echo $row['name'];
                    echo '</label>';
                    echo '</div>';
                }
			$stmt = null;
			$conn = null;

Then, heres how I show All the amenities, and have the given amenities checked

foreach($amenities as $amenity => $checked){
    if( 'Y' === $checked ){
      $checked = 'checked';
    }
echo '<div class="checkbox col-sm-4">';
echo '<label>';
echo '<input type="checkbox" name="Amenities[]" value="'.$amenity.'" '.$checked.'>';
echo '<span class="cr"><i class="cr-icon fa fa-check"></i></span>';
echo $amenity;
echo '</label>';
echo '</div>';
echo "\n";
}

How do I change make it so an DELETE runs only if an amenity is deselected and an INSERT runs if a new amenity is selected?

One thing to keep in mind when dealing with checkboxes is that when the form data is submitted, for any checkbox fields, if they aren’t checked then nothing gets sent for them

Well you could go and get all complicated comparing previous and POST arrays but the simplest way is just to delete all amenities for the propertyID, then insert all that are checked. This is the most reliable way to make sure you don’t have duplicates and only selected amenities for the property.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.