Hi, I’m having an issue adding data from checkboxes on a form into a MySQL query. I’ve checked a number of examples but they all seem to be slightly different to my setup and nothing I’ve tried so far has worked.
Basically the form displays five photo filenames from a database, so the images are displayed, along with a checkbox that will say “Check here if you want to delete this photo”.
I set up the various checkbox inputs as an array, as recommended:
if (!empty($row['pic1'])) { echo '<div class="editpics"><img src="images/carpictures/' . $pic1 . '" width="100"><br /><label for="Pic[]">Delete Photo 1</label><input name="Pic[]" type="checkbox" class="formfield" value="'.$pic1.'" /></div>'; }
if (!empty($row['pic2'])) { echo '<div class="editpics"><img src="images/carpictures/' . $pic2 . '" width="100"><br /><label for="Pic[]">Delete Photo 2</label><input name="Pic[]" type="checkbox" class="formfield" value="'.$pic2.'" /></div>'; }
if (!empty($row['pic3'])) { echo '<div class="editpics"><img src="images/carpictures/' . $pic3 . '" width="100"><br /><label for="Pic[]">Delete Photo 3</label><input name="Pic[]" type="checkbox" class="formfield" value="'.$pic3.'" /></div>'; }
if (!empty($row['pic4'])) { echo '<div class="editpics"><img src="images/carpictures/' . $pic4 . '" width="100"><br /><label for="Pic[]">Delete Photo 4</label><input name="Pic[]" type="checkbox" class="formfield" value="'.$pic4.'"/></div>'; }
if (!empty($row['pic5'])) { echo '<div class="editpics"><img src="images/carpictures/' . $pic5 . '" width="100"><br /><label for="Pic[]">Delete Photo 5</label><input name="Pic[]" type="checkbox" class="formfield" value="'.$pic5.'" /></div>'; }
So the above code checks to see if there’s a photo in the database and will display it if there is. The values of the checkboxes are the filenames of each of each of the photos.
So when this is submitted, I want the form handler to check each of these checkbox inputs, and for every one that’s checked, change the field value for that photo to blank. So for example if we no longer want Pic3, we check it in the form, and the form handler changes the database entry for the photo for that record from (e.g) somepicorother.jpg, to just nothing.
I didn’t get very far with the form handler script, so this is clearly incomplete:
if($_POST['deletephotos']) //if the form is submitted
{
$carid = $_POST['_CarID']; //this is to make sure we only edit photos for the specified record
$pic = $_POST['Pic'];
foreach ($_POST['Pic'] as $key => $value) {
$updatestockdetails = $mysqli->query("UPDATE cars SET " ); //Not sure how to complete this query
if ($updatestockdetails) {echo "<p>Selected photos deleted successfully.</p>"; }
}
The various photo fields in the db are called Pic1, Pic2, Pic3, Pic4 and Pic5.
I guess I’m trying to figure a way of only getting the field value changed if the appropriate checkbox has been checked, I can’t figure a way of doing this in the query.