How can i make a function out of this code

where all colored red variable is dynamic...meaning i can change the variable
according to dept table, branch table

Code:
$query4="SELECT * FROM tblbranch";
$result4 = mysql_query ($query4);
echo "<select name=Branch id=textbox value=''>Branch</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result4)){//Array or records stored in $nt
echo '<option '.($nt['branchcode'] == $bra ? ' selected ' : '').' value="'.$nt['branchcode'].'" >'.$nt['branchcode'].'-'.$nt['branchdesc'].'</option>'; 
}
echo "</select>";// Closing of list box */
?>