Zend - The PHP Company




Forms

Add Code


Create dynamic select boxes from a database with this function  

Type: code fragment
Added by: rayray
Entered: 02/08/2000
Last modified: 08/12/1999
Rating: **** (7 votes)
Views: 22798
This function allows you to pass in:
  • name
  • table
  • SQL statement
  • id
to generate a select box dynamically. Optionally you can pass in an $id to have it create a select box with a specific value set as "selected".


<?php
function createSelect $Sname$table$any 0$select_id="" ) {
# $Sname is the name to be applied to the select control.
# $table is the name of the table to query.
# NOTE: This function assumes you are using a lookup table that has 2 fields (id,name) or you only name those 2 fields in your sql statement.
# $any 0=Without the "Any" option, 1=With the "Any" option, this is a NULL value. 
# $curr_id is used to set the "SELECTED" flag on the select control.

    
include("../etc/global.inc");
    
$dbh =  mysql_connect($host,$user,$pass);
    
mysql_select_db($dbname);
    
$sql "SELECT * FROM $table";
    
$results mysql_query($sql);
    
printf("<select name="$Sname">n");
    if (
$any == 1) {
    
printf("<option "">Anyn");
    }
    while (
$row mysql_fetch_array($results)):
        
$id $row["id"];
        
$name $row["name"];
        if (
$id == $select_id) {
            
printf("<option SELECTED value="$id">$namen");
        } else {
            
printf("<option value="$id">$namen");
        }
    endwhile;
    
printf("</select>n");
}    
?>


Usage Example


//"Type" is the name of the created select box.
//"type" is the name of the table to query.
//1 is the flag to set a null value for an option called "Any" this is hand for searching. This argument is optional.
<?php createSelect("Type","type",1);?>


Rate This Script





Search



This Category All Categories