While in a while loop

I have two tables (amenities & properties)
The amenities table simply holds all the amenities,
Each property has several amenities (linked to it by another table (properties_amenities)
Am trying to figure out how to have each amenity as a checkbox, but have the selected properties amenities all ready checked?
This is what I have so far

           $stmt = $conn->query('SELECT name FROM amenities');
			
			$conn2 = new PDO("mysql:host=$hostname;dbname=shores", $username, $password);

            $stmt2 = $conn2->query('SELECT amenity FROM properties_amenities WHERE propertyID='.$_GET['id']);
			
			//var_dump($stmt->errorInfo());
			//echo "<br>";
			//var_dump($stmt2->errorInfo());
			$row2 = $stmt2->fetch();
			while ($row = $stmt->fetch()) :
				while($row2=$stmt2->fetch()) {
				$isChecked = $row2['amenity'] === $row['name'] ? 'checked' : '';
				}
			  ob_start(); ?>
			
				<div class="checkbox">
				  <label>
					<input type="checkbox" name="Amenities[]" value="<?= $row['name'] ?>" <?= $isChecked ?>>
					<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>
					<?= $row['name'] ?>
				  </label>
				</div>
				
			  <?php echo ob_get_clean();
			endwhile;

But the result


So at least each amenity is there, but how do I get the 3 checked?

Isn’t this just another version of the same question you asked in another thread, which has had some answers and some sample code?

The problem with this code is that you run the two queries, then you retrieve the first property-amenity. You then retrieve all of the master amenities rows, check each one to see if it’s the same, then display the checkbox, possibly with “checked” after it.

Because you loop through all the amenities list this first time, and don’t exit the loop when you find a match, you will only have “checked” if the last amenity that you compare has a hit - if it does not, then the next in the loop will overwrite the answer. Just a simple var_dump() after your inner while loop would show you that result.

The second issue is that when you run the second iteration of the outer while loop, your inner while won’t retrieve anything because the query has already given you all the results the first time you asked. A simple echo inside that loop would show you it was retrieving nothing.

So with the code you have above, the only time you’ll see a checkbox ticked is if the first property-amenity you get back in the outer loop happens to be the same as the last amenity you get from the master amenities table. It might be, because you don’t order the results. But it’s not what you want.

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