Linked dynamic Select-Boxes with PHP & JavaScript

Script reads the values from 2 linked database tables and generates 2 select boxes – the first holds the categories and if one category is checked, the second box displays the depending values without reloading the site. You can now access the values of the select boxes via form operations.

Notice:
I used ADODB for the database queries – more information.

<?php
/* ########################################################
28.09.2004, by Elmar Putz
http://www.elp.co.at

ADODB - source
http://adodb.sourceforge.net

Connecting de Database with ADODB

$db = ADONewConnection($databasetype);
$db->debug = false;
$db->PConnect($server, $user, $password, $database);

##########################################################
*/
/* DB-Tables

------------------------
prod_typ_1
------------------------
id     int(11)
typ_titel_de   varchar(50)
typ_titel_en   varchar(50)

------------------------
prod_typ_2
------------------------
id     int(11)
titel_de   varchar(50)
titel_en   varchar(50)
typ_1_id int(11)  // verknüpfung zu prod_typ_1.id
*/

// Data query

$sql1 = "SELECT prod_typ_1.id, prod_typ_1.typ_titel_de, prod_typ_2.id, prod_typ_2.titel_de
FROM prod_typ_1 INNER JOIN prod_typ_2 ON prod_typ_1.id = prod_typ_2.typ_1_id  order by prod_typ_1.id, prod_typ_2.titel_de";
$rsX = $db->execute($sql1);

// type listbox...

echo "<SELECT NAME=\"typ1\" SIZE=\"1\" ONCHANGE=\"manuselected(this); document.form1.typ2.style.visibility = 'visible';\" class=\"formular\">";
// write the entry code for the javascript...
echo "<option value=\"\">Typzuordung ändern</option>";

$sJavaScript = "function manuselected(elem)
{
for (var i = document.form1.typ2.options.length; i >= 0; i--)
{ document.form1.typ2.options[i] = null;";

// loop through the recordset...

while (!$rsX->EOF)
{
If ($sLasttype <> $rsX->fields[1])
{

// if so, add an entry to the first listbox

$sLasttype = $rsX->fields[1];
echo "<OPTION VALUE=" . $rsX->fields[0] . ">" . $sLasttype ."</OPTION>";

// and add a new section to the javascript...

$sJavaScript = $sJavaScript . "}
if (elem.options[elem.selectedIndex].value==".$rsX->fields[0].")
{";
}

// and add a new model line to the javascript...

$sJavaScript = $sJavaScript .
"document.form1.typ2.options[document.form1.typ2.options.length] = new Option('".$rsX->fields[3]. "','" . $rsX->fields[2] ."');\n";
$rsX->MoveNext();
}
// finish the Typ 1 listbox...

echo "</SELECT>    ";
// create the Typ 2 listbox...

echo "<SELECT NAME=\"typ2\" SIZE=\"1\" class=\"formular\" style=\"visibility: hidden;\">
<OPTION>Keine Auswahl</OPTION>
</SELECT>";

// put the last line on the javascript...
// and write it out...

$sJavaScript = $sJavaScript . "}\n
}\n" ;
echo "<SCRIPT LANGUAGE=\"JavaScript\">\n";
echo $sJavaScript ."\n</SCRIPT>";

?>

Leave a Reply

Your email address will not be published. Required fields are marked *