Dynamic HTML Select Option List From Database Tables

Here we provide instruction how to get the data dynamically to HTML form select elements. Below functions already in utility files. You may download it.


Database Table to Array:

CopiedCopy Code


<?php
//@$index=> single field name. Array Index. [Optional]
//@$field=> single field name. Array Value. [Optional]
//$type=> default :NULL, type set to "subarray" then get same index record in sub array, type set to jsonarr then get json reocrds in array [Optional]
function getRecords($query='',$index='',$field='',$type=NULL) {
if($query=='') return false;
$arr=array();
$i=0;
$totrecords=$this->query($query,"select");
if($totrecords>0) {
if($type=="jsonarr" && $index!='' && $field!='') {
while($fetch=$this->fetch_records())
{ $arr[$i++]="'".$fetch[$index]."':'".$fetch[$field]."'";
}
// convert above array to JSON String '{'.implode(',',$arr).'}' after return
}
else if($type=="subarray") {
while($fetch=$this->fetch_records()) {
if($index!='')
$arr[$fetch[$index]][]=($field!='')?$fetch[$field]:$fetch;
else
$arr[$i++][]=($field!='')?$fetch[$field]:$fetch;
}
}else {
while($fetch=$this->fetch_records()) {
if($index!='')
$arr[$fetch[$index]]=($field!='')?$fetch[$field]:$fetch;
else
$arr[$i++]=($field!='')?$fetch[$field]:$fetch;
}
}
}
return $arr;
}
?>

Table: axispower

id country
1Italy
2Germany
3Japan

CopiedCopy Code


<?php
$axis_power=$db->getRecords("SELECT id,name FROM axispower","id","name");
echo '<pre>';
print_r($axis_power);
echo '</pre>';

?>
/*
HTML Output

Array
(
[1] => Italy
[2] => Germany
[3] => Japan
)
*/

PHP Array to List:

CopiedCopy Code


<?php
function getArray2List($arr,$default=0,$start=0) {

$start=(int)$start;
if(is_array($arr) && count($arr)>0)
foreach($arr as $key=>$value) {

$key=($start>0)?($start++):$key;

$opt.='<option value="'.$key.'"';
if($default==$key) $opt.='selected="selected"';
$opt.='>'.$value.'</option>';
}
return $opt;
}

?>


Usage:

CopiedCopy Code


<?php
$axis_power=array(1=>"Italy",2=>"Germany",3=>"Japan");
?>
<select name="axispower">
<?php
echo getArray2List($axis_power,2); // Default Selection: Germany
?>
</select>

CopiedCopy Code


<?php
//Download the country SQL from right side bar
$country_array=$db->getRecords("SELECT country_id,country_name,country_3_code,country_2_code FROM cdyn_country","country_id","country_name");
?>
<select name="country">
<?php
echo getArray2List($country_array,1);
?>
</select>