You are on page 1of 1

Databind dropdown list (select) in PHP

Being new to PHP, it may occur to you about how to databind controls. I thought of putting it down here
about how to do it. To start with we create the connection and query the database.

<?php
$link = mysql_connect("localhost","dbuser","password");

if (!$link) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db("mydatabase");
$sql = mysql_query("select * from employee");?>

Then add the select statement
<select name="dropdownlist">
<?php
while($row = mysql_fetch_array($sql))
{
?>
<option value=" <?php echo $row['ID']?>">
<?php echo $row['EmpName'] ?></option>
<?php } ?>
</select>

Each row is fetched into $row and the column values can be access by passing the column name like
$row['EmpName'] as in above example, the value of option is assigned from ID and the text is added from
EmpName.

You might also like