Online free tutorials of html php mysql and asp.net

Select Option from mysql database

For making select options from mysql database, we make table with name "countries" in mysql database and fill some names as given blow.



id country
1 Afghanistan
2 Albanie
3 Algérie
4 Bahamas
5 Bahreïn
6 Bangladesh
7 Canada
8 Chili
9 India
10 USA
After making table, we are going to make function, which returns an array with id and countries from mysql table;
<?php
function getCountries(){
$host="localhost";
$username="user_name";
$password="password";
$db="database_name";
$items=array();
$link=mysql_connect($host,$username,$password);
if($link)
{ //connection is opened
mysql_select_db($db,$link) or die("could not select database".mysql_error());
$query="SELECT * FROM countries";
$result=mysql_query($query);
while($row=mysql_fetch_row($result)){
$items[$row['id']]=$row['country'];
}
mysql_close($link);
}
else
 { //otherwise gives error
  echo mysql_error();
  }
return $items;
}
//Our next step is making HTML form, So make form as given.
?>

<form name="form1" action="simple_fom_result.php" method="post"> <table> <tr><td>First Name</td><td><input type="text" name="first_name" id="first_name" /></td></tr> <tr><td>Last Name</td><td><input type="text" name="last_name" id="last_name" /></td></tr> <tr><td>Gender </td> <td> <input type="radio" name="gender" id="gernder-1" value="male" checked="checked" /> Male <input type="radio" name="gender" id="gernder-2" value="female" /> Female
</td></tr> <tr><td>Country </td><td> <select name="country" id="country" > <?php $options=getCountries(); foreach($options as $key=>$val){ ?> <option value="<?php echo $key ?>"><?php echo $val?></option> <?php } ?> </select> </td></tr> <tr><td>Your Hobbies </td><td> <textarea name="hobbies" id="hobbies" rows="5" cols="36"></textarea> </td></tr> <tr><td></td><td><input type="submit" name="btn" id="btn" value="Submit" /></td></tr> </table> </form>