What are the best practices for dynamically populating checkboxes in PHP based on database values?

When dynamically populating checkboxes in PHP based on database values, it is important to first query the database to retrieve the necessary data. Then, loop through the results and create a checkbox input for each value, checking if the checkbox should be pre-selected based on the database values. Finally, output the checkboxes within a form to allow for user interaction.

// Query the database to retrieve values for checkboxes
$query = "SELECT id, value FROM checkboxes_table";
$result = mysqli_query($connection, $query);

// Loop through the results and create checkboxes
while ($row = mysqli_fetch_assoc($result)) {
    $checked = ($row['value'] == 'selected') ? 'checked' : '';
    echo '<input type="checkbox" name="checkbox[]" value="' . $row['id'] . '" ' . $checked . '>' . $row['value'] . '<br>';
}