Use a checkbox to update a mysql table

I’m trying to turn the display field for the record to either 1 or 0 (depending on if the box is checked or not)
I got the form to display

	while($row = $stmt->fetch()) {
		
		switch($row['display']) {
		
		case 1:
			$display = 'checked';
			break;
		default:
			$display = '';
			break;
		}

	  echo '<tr>';
	  echo "<td>".$row['id']."</td>";
	  echo '<td>'.$row['userName'].' ('.$row['userID'].')</td>';
	  echo '<td><input type="hidden" name="userID['.$row['id'].']" value="'.$row['id'].'"><input type="checkbox" name="display['.$row['id'].']" value="'.$row['display'].'" '.$display.'></td>';
	  echo '</tr>';
	  echo "\r\n";

But how do I make it so that once the form is submitted, i only change the changed display property (1 or 0) in the mysql table?

Thanks

Have a look at the contents of your $_POST array, in particular the names of the checkboxes that are included. If I’m reading your HTML correctly, you’ve named them using the ID field, so you should be able to iterate through them using foreach() to update your database.

I don’t see the point in your hidden variable, as that just duplicates things, by using the ID as both the array index and the value. You could do something like that to provide the original value of the checkbox, so you can see whether the database needs to be updated for each entry.

If you don’t specify a value in your <option> tag, the display string is sent through as the value. On each of your <select> tags, you have the first option that contains either No or Yes, with no specific value set, so if that selection isn’t changed, it will send the string. If these are coming from a database in the real code, it might be better to set the selected flag on the appropriate option, rather than adding another one.

In your foreach() loop to run the query, I’d have the prepare() before the loop is executed, then just call it each time. I doubt it will make any difference to perceived execution time, but one of the features of prepared statements is the ability to prepare it once and then just keep calling it with new parameters so it seems “right”.Yes. Call the prepare before the loop and just pass your array in to execute in each iteration of the loop. I usually use bindParam() rather than passing an array, so I would put both of those statements before the loop, then just set the correct values within the loop and call execute.

source:-.sitepoint.