Zend - The PHP Company




Forms

Add Code


make listbox from array or database-table  

Type: code fragment
Added by: wibi
Entered: 07/05/2001
Last modified: 05/12/2000
Rating: - (fewer than 3 votes)
Views: 12744
This script contain 2 function to make a drop-down-menu from an array and from mysql-database table.


<?
/********************************************************************
*    drop-down-menu - form field function.
*    2 function that return a drop-down-menu
*   Syntax :
*        - string listbox_array(array list, string name, int selected-item);
*            - list is an array you want to dump into drop-down-menu form-field
*
*        - string listbox_field(int mysql_link, string name, int selected-item);
*            - mysql_link is a valid mysql_result from QUERY SELECT command
*
*    Copyright (C) 2001 Wibisono Sastrodiwiryo. 
*       This program is free software licensed under the 
*       GNU General Public License (GPL).
*
*   CyberGL => Application Service Provider
*   http://www.cybergl.co.id
*    office@cybergl.co.id
*
*   $Id: listbox.php3,v 0.1 2001/04/25 21:6:31 wibi Exp $ 
*********************************************************************/

function listbox_array ($list$name$default=0$associative=0) {
    
$result="<select name="$name" size=1>n";
    while (list(
$key$val) = each($list)) {
        if (
$associative) {
            if (
$default  == $key) {$selected="selected";} else {$selected="";}
            
$result.="<option value="$key$selected>$val</option>n";
        } else {
            if (
$default  == $val) {$selected="selected";} else {$selected="";}
            
$result.="<option value="$val$selected>$val</option>n";
        }
    }
    
$result.="</select>n";
return 
$result;
}

#---listbox_field()-function only work under establish mysql connection

function listbox_field ($mysql_link$name$default=0) {
    
$result="<select name="$name" size=1>n";
    while (list(
$key,$val)=mysql_fetch_array($mysql_link)) {
        if (
$default  == $key) {$selected="selected";} else {$selected="";}
        
$result.="<option value="$key$selected>$val</option>n";
    }
    
$result.="</select>n";
return 
$result;
}
?>


Usage Example


<?
require("listbox.php3");
?>
<form>
<p>
Gender : 
<?
$gender
=array("female""male""bencong");
echo 
listbox_array($gender"gender""male");
?>
<p>
Modem speed : 
<?
$modem
=array("33.6"=>"slow","64"=> "medium","128"=> "fast");
echo 
listbox_array($modem"modem""64"1);
?>
<p>
Country : 
<?
#----------open database connection
mysql_pconnect("localhost""root""password") or die("Unable to connect to SQL server");
mysql_select_db("cybergl") or die("Unable to select database");

#----------there must be a table called country with two fields
$country=mysql_query("SELECT code, name FROM country");
echo 
listbox_field($country"country""ID");
?>
</form>


Rate This Script





Search



This Category All Categories