<?php
/*
Database: `testdb`
Table structure for table `groupnames`
DROP TABLE IF EXISTS `groupnames`;
CREATE TABLE IF NOT EXISTS `groupnames` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`groupname` varchar(50) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
Dumping data for table `groupnames`
INSERT INTO `groupnames` (`id`, `groupname`, `name`) VALUES
(1, 'Admins', '1'),
(2, 'Admins', '2'),
(3, 'Editors', '3'),
(4, 'Editors', '4'),
(5, 'Basic Users', '5'),
(6, 'Basic Users', '6');
COMMIT;
*/
$conn = mysqli_connect("localhost","root","","testdb"); //server,username,password,database
if(!$conn){
die("Database Connection Failed."); //if wrong server name,username,password or database name
}
if(isset($_POST['submit'])){
$grouplabel_name = $_POST['grouplabel_name'];
echo $grouplabel_name; //displays the group label name and name from the group
}
?>
<form method="post" action="">
<select name="grouplabel_name">
<option></option>
<?php
$query = mysqli_query($conn,"SELECT * FROM groupnames ORDER BY id ASC")or die(mysqli_error($conn));
while($row = mysqli_fetch_object($query)){
$grouplabel = $row->groupname; //group label
$name = $row->name; //name from the group
if($grouplabel == "Admins"){
?>
<optgroup label="Admins">
<option value="<?php echo $grouplabel.' - '.$name; ?>"><?php
if($name == 1){
echo "John Smith";
}
elseif($name == 2){
echo "Jane Smith";
}
?>
</option>
</optgroup>
<?php
}
elseif($grouplabel == "Editors"){
?>
<optgroup label="Editors">
<option value="<?php echo $grouplabel.' - '.$name; ?>"><?php
if($name == 3){
echo "Brian Smith";
}
elseif($name == 4){
echo "Scott Smith";
}
?>
</option>
</optgroup>
<?php
}
elseif($grouplabel == "Basic Users"){
?>
<optgroup label="Basic Users">
<option value="<?php echo $grouplabel.' - '.$name; ?>"><?php
if($name == 5){
echo "Kevin Smith";
}
elseif($name == 6){
echo "Tanya Smith";
}
?>
</option>
</optgroup>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
希望对你有帮助:)