What is the best way to automatically set a radio input value based on existing data from a database in PHP?
When setting a radio input value based on existing data from a database in PHP, the best way is to retrieve the data from the database and then use conditional statements to check if the value matches the data. If it does, add the "checked" attribute to the radio input. This can be achieved by using PHP to dynamically generate the radio input with the appropriate value and checked attribute based on the database data.
<?php
// Assume $data is the value retrieved from the database
$data = "option2";
$options = ["option1", "option2", "option3"];
foreach ($options as $option) {
if ($option == $data) {
echo '<input type="radio" name="radio_input" value="' . $option . '" checked>' . $option . '<br>';
} else {
echo '<input type="radio" name="radio_input" value="' . $option . '">' . $option . '<br>';
}
}
?>