嗨,我有这个mysql表。
CREATE TABLE IF NOT EXISTS `selling_counties` ( `county_id` int(11) NOT NULL auto_increment, `country` varchar(20) collate utf8_unicode_ci NOT NULL, `county_name` varchar(25) collate utf8_unicode_ci NOT NULL, `datecreated` datetime NOT NULL, `datemodified` datetime NOT NULL, PRIMARY KEY (`county_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=97 ;
并且我需要一个带有optgroup的selectbox,其中country将是,County_name将是s,例如
<select name ="county"> <optgroup label="England"> <option>South Yorkshire</option> <option>Staffordshire</option> <option>Suffolk</option> <option>Surrey</option> <option>Tyne and Wear</option> <option>Warwickshire</option> <option>West Midlands</option> <option>West Sussex</option> <option>West Yorkshire</option> <option>Wiltshire</option> <option>Worcestershire</option> </optgroup> <optgroup label="Wales"> <option>Clwyd</option> <option>Dyfed</option> <option>Gwent</option> <option>Gwynedd</option> <option>Mid Glamorgan</option> <option>Powys</option> <option>South Glamorgan</option> <option>West Glamorgan</option> </optgroup> <optgroup label="Scotland"> <option>Aberdeenshire</option> <option>Angus</option> <option>Argyll</option> <option>Selkirkshire</option> <option>Shetland</option> <option>Stirlingshire</option> <option>Sutherland</option> <option>West Lothian</option> <option>Wigtownshire</option> </optgroup> <optgroup label="Northern Ireland"> <option>Antrim</option> <option>Armagh</option> <option>Down</option> <option>Fermanagh</option> <option>Londonderry</option> <option>Tyrone</option> </optgroup> </select>
我已经尝试过这个PHP:使用optgroup进行动态下拉, 但是对我来说有点复杂,因为我是php的新手,而且它来自2个单独的表,而我来自同一个表。
任何帮助将是非常可贵的。
您需要从表中选择值
$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']); }
并将它们放在您的html select中。
更新 添加county_id在<option>:
county_id
<option>
<option value="<?php echo htmlentities($county[0]); ?>"><?php echo htmlentities($county[1]); ?></option>