
How to Use MySQL ENUM Type Field to Populate the DOM
Posted on Dec 11, 2021
1) Make your table:
CREATE TABLE IF NOT EXISTS `users` (
`sex` ENUM('Male', 'Female') DEFAULT 'Male'
) ENGINE=INNODB;
2) Put the SELECT tag on your page:
<select class="form-control" id="gender" name="gender">
</select>
3) The PHP goes in the SELECT tag:
<?php
// Database Connection Script (PDO) here
$genderstmt = $conn->query( "SHOW COLUMNS FROM `users` LIKE 'sex'" );
while ( $row = $genderstmt->fetch() ) {
$columntype = $row[ 'Type' ];
$columndefault = $row['Default'];
}
$output = str_replace( "enum('", "", $columntype );
$output = str_replace( "')", "", $output );
$results = explode( "','", $output );
// now output the array items as HTML Options
for ( $i = 0; $i < count( $results ); $i++ ) {
echo '<option value="' . $results[ $i ] . '"'.($results[$i]==$columndefault?' selected':'').'>' . $results[ $i ] . '</option>';
}
?>
4) Output
<select class="form-control" id="gender" name="gender">
<option value="Male" selected="">Male</option>
<option value="Female">Female</option>
</select>
EDIT: If you want to use input[type="radio"] instead, in the for() loop write this instead (oh and make sure it isn't in a SELECT tag)
for ( $i = 0; $i < count( $results ); $i++ ) {
echo '<input type="radio" name="gender" value="' . $results[ $i ] . '"' . ( $results[ $i ] == $columndefault ? ' checked' : '' ) . '>';
echo '<label for="' . $results[ $i ] . '">' . ucwords( $results[ $i ] ) . '</label><br>'; // the <br> is optional if you want everything on the same line
}
The output
<input type="radio" name="gender" value="male" checked="">
<label for="male">Male</label><br>
<input type="radio" name="gender" value="female">
<label for="female">Female</label><br>
If you need to add or remove options, all you have to do in SQL is:
-- To add more genders
ALTER TABLE `users` MODIFY COLUMN `sex` enum('Male', 'Female', 'X') DEFAULT 'X';
-- To remove genders
ALTER TABLE `users` MODIFY COLUMN `sex` enum('Female') DEFAULT 'Female';
Search
Recent Posts
Categories
- Entertainment
- Viewing Orders
- Viewing Orders
- IT
- Tutorials
- PHP & MySQL
- VanillaJS & Bootstrap 5
- PHP & MySQL