Populate a dropdown by fetching data from database


Posted on 30 Jan 15 by Vickey

If you are creating a dynamic dropdown which options should come from database. For this you can use the below code. In the below function you can pass table name fields which you want set as option values and options text and you can give database conditions also

Here is instructions for parameters

id :  this will be the dropdown id

tableName : this is table name from which you want to fetch data

fieldText : your datbase table field which you want to show as option text

whereCondition : if you want to fetch data by using a condition you can give condition

Here are also parameter for add events also like 'onchange' 

echo selectBox($id, $tableName,$fieldText, $fieldValue, $whereCondition='', $orderBy='', $eventFunction='', $defaultValue='', $helpText='', $disable='', $width='', $controlName='', $printQuery=0, $cssClass='',$addtionItems='');
public function selectBox($id, $tableName,$fieldText, $fieldValue, $whereCondition='', $orderBy='', $eventFunction='', $defaultValue='', $helpText='', $disable='', $width='', $controlName='', $printQuery=0, $cssClass='',$addtionItems='')

    $controlName = $id;

    $cssClass = "class=$cssClass";

    $eventFunctionOnChange = " onchange='$eventFunction'";

    $selectBox .=  "";
    return $selectBox;

Please feel free to write a comment


You can download source code here

If this post help you reduce time to develop, you can help me to maintain this website :)