Php Programming Code Examples
Php > Databases Code Examples
Function to do live population of HTMLs Select tag from a Table
Function to do live population of HTMLs Select tag from a Table
<?
/*
Description:
This function takes several arguments and generates
the <OPTION..>...</OPTION> HTML code fragment. A mysql_connect() is presumed
to exist already.
Arguments passed:
$dbname (required) Database name
$tblname (required) Table name
$tblkeyvarname (required) Name of table's key field
$tblkeyvaluesname (required) Name of column that describes key field (usually the
displayable value in the <select> options)
$defval (optional) Default key value, if any. <select> displays
this value by default
Return Value(s) $success: returns 1 if query was successful, 0 if query
failed
Usage: To use this, construct the following code in your .PHP file --
- - - - - - - - - - - - -
<? require("fx_populateselectoptions.inc"); ?>
<HTML>
...
<BODY>
...
<SELECT...>
<?php
PopulateSelectOptions ( $dbname,
$tblname,
$tblkeyvarname,
$tblvaluesname,
$defval
);
?>
</SELECT>
...
</BODY>
</HTML>
- - - - - - - - - - - - -
-----------
START FN:
-----------
*/
function PopulateSelectOptions ( $dbname, $tblname, $tblkeyvarname, $tblvaluesname,
$defval ) {
// Check passed arguments
if ( empty($dbname) ) {
echo "<!-- PopulateSelectOptions() Error: Database Name had no value --
>\n";
return 0;
}
if (empty($tblname) ) {
echo "<!-- PopulateSelectOptions() Error: Table name had no value -->\n";
return 0;
}
if (empty($tblkeyvarname) ) {
echo "<!-- PopulateSelectOptions() Error: Key Field name had no value --
>\n";
return 0;
}
if (empty($tblvaluesname) ) {
echo "<!-- PopulateSelectOptions() Error: Variable name for List Values
had no value -->\n";
return 0;
}
$success=0;
// Set up table query
$local_qry = "select * from " . $tblname;
$localresult=mysql_db_query( $dbname, $local_qry );
echo "<!-- DefVal passed was = " . $defval . " -->";
// Construct HTML code
if ($localresult) {
while( $row=mysql_fetch_array($localresult) ) {
echo "<option";
if ( isset($defval) ) {
if ( $row["$tblkeyvarname"]==$defval ) {
echo " selected ";
}
}
if (is_string($tblkeyvarname)) {
echo " value='".$row["$tblkeyvarname"]."'>";
} else {
echo " value=".$row["$tblkeyvarname"].">";
}
echo $row["$tblvaluesname"];
echo "</option>\n";
}
$success=1;
}
// Check if query was successful
if (!$success) {
if (!$localresult) {
echo "<!-- PopulateSelectOptions() Error: Could not access
database and/or table ".$dbname.".".$tblname.". -->\n";
}
}
return $success;
}
?>