How To Generate Dynamic Selectbox With Optgroup
Hi I am having this mysql table. CREATE TABLE IF NOT EXISTS `selling_counties` ( `county_id` int(11) NOT NULL auto_increment, `country` varchar(20) collate utf8_unicode_ci NOT
Solution 1:
Create a new array like this, with countries as the keys, and the array of counties as each value. Assuming $rows is the array of raw table rows.
<?php$countries = array();
foreach($rowsas$row)
{
if(isset($countries[$row['country']])) // <-- edit, was missing a ]
{
$contries[$row['country']][] = $row['county_name'];
}
else
{
$countries[$row['country']] = array($row['county_name']);
}
}
?><selectname ="county"><?phpforeach($countriesas$country => $counties): ?><optgrouplabel="<?phpecho htmlentities($country); ?>"><?phpforeach($countiesas$county): ?><option><?phpecho htmlentities($county); ?></option><?phpendforeach; ?></optgroup><?phpendforeach; ?></select>Solution 2:
You need to select the values from your table
$mysqli = new mysqli($host, $user, $passwd, $database);
$result = $mysqli->query('select county_id, country, county_name from selling_counties');
$countries = array();
while ($row = $result->fetch_assoc()) {
$country = $row['country'];
if (!array_key_exists($country, $countries))
$countries[$country] = array();
$countries[$country][] = array($row['county_id'], $row['county']);
}
and put these in your html select.
Update to add county_id in <option>:
<optionvalue="<?phpecho htmlentities($county[0]); ?>"><?phpecho htmlentities($county[1]); ?></option>
Post a Comment for "How To Generate Dynamic Selectbox With Optgroup"