Populate a dropdown in PHP: example

from the Artful MySQL Tips List



<html>
<head>
<script type='text/Javascript'>
    function submit( f ) {
      f.submit();
    }
  </script>

</head>
<body>
<form>

<?php
$conn 
mysqli_connnect(...);
$resfoo mysqli_query$conn"SELECT foo FROM footable" ) or die( "Cannot retrieve foo values" );
echo 
"<b>Foo Value:</b> \n";
echo 
" <select name='foo' onChange='submit(this.form)'>\n";
while( 
$row mysqli_fetch_row$resfoo )) {
  
$sel = ( $table === $row[0] ) ? "id='sel' selected" "";
  
printf" <option %s value='%s'>%s</option>n"$sel$row[0], $row[0] );
}
echo 
" </select>\n";
echo 
" <input id='edit' type='button' value='Pick a foo' onClick='submit(this.form)'>\n";
?>


</form>
</body></html>

Last updated 6 Feb 2025


Return to the Artful MySQL Tips page