Connecting Tech Pros Worldwide Forums | Help | Site Map

PHP - Dynamic Drop Down Menu

Newbie
 
Join Date: Mar 2006
Posts: 12
#1: Mar 6 '06
Hi,

I'm fairly new to PHP and I've created a dynamic drop down menu that populates itself with data from a MySQL table. What I would like to do is create a non dynamic drop down menu that alters what is shown in the dynamic menu.

For example, the first menu has three cities London, Paris, New York. If I choose London it populates the second menu with people from London.

Here is the code I have for my dynamic menu

Expand|Select|Wrap|Line Numbers
  1. <td valign=top><strong>Name:</strong></td>
  2.     <td>
  3.     <?php
  4.     echo "<select name=\"name\">"; 
  5.     echo "<option size =30 selected>Select</option>";
  6.     if(mysql_num_rows($sql_result)) 
  7.     { 
  8.     while($row = mysql_fetch_assoc($sql_result)) 
  9.     { 
  10.     echo "<option>$row[name]</option>"; 
  11.     } 
  12.  
  13.     } 
  14.     else {
  15.     echo "<option>No Names Present</option>";  
  16.     } 
  17.     ?>
  18.     </td>
  19.     </tr>    
  20.  
So basically, I need a standard menu, i.e:

Expand|Select|Wrap|Line Numbers
  1. <tr>
  2.     <td valign=top><strong>Sites:</strong></td>
  3.     <td> <select name="cities">
  4.     <option selected>Select</option>
  5.     <option>London</option>
  6.     <option>Paris</option>
  7.     <option>New York</option>
  8.     </select>
  9.     </tr>
  10.     </td>
  11.  
I think I need to hold the value of cities when selected in a variable and create an if statement with various sql query results to be run depending on what option is chosen.

Any help would be highly appreciated!

Thanks,
Mart

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,202
#2: Mar 7 '06

re: PHP - Dynamic Drop Down Menu


I think you may have forgotten or not understood that PHP runs of the server and the implications of this.

PHP runs on the server as you request a page returning the required output. This output may be obtained from a MySql database or any other sourse that PHP can access.

What this means though is that if you want to generate source using PHP you have to make a server request of some sort.

In practive this means for a simple page either reloading the current or a new page or loading a page in an IFRAME.

However I get the impression that you want to have a single page with 2 selection boxes on it and fill one depending on what the selection in the other is.

It is possible (I have never done it) using XML requests to reload content in a div without reloading the rest of the page using code that looks something like

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.  
  3. /***********************************************
  4. * Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
  5. * This notice MUST stay intact for legal use
  6. * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
  7. ***********************************************/
  8.  
  9. var loadedobjects=""
  10. var rootdomain="http://"+window.location.hostname
  11.  
  12. function ajaxpage(url, containerid){
  13.   var page_request = false
  14.  
  15.   if (window.XMLHttpRequest) // if Mozilla, Safari etc
  16.     page_request = new XMLHttpRequest()
  17.   else if (window.ActiveXObject){ // if IE
  18.     try {
  19.       page_request = new ActiveXObject("Msxml2.XMLHTTP")
  20.     } 
  21.     catch (e){
  22.       try{
  23.         page_request = new ActiveXObject("Microsoft.XMLHTTP")
  24.       }
  25.       catch (e){}
  26.     }
  27.   }
  28.   else
  29.     return false
  30.  
  31.   page_request.onreadystatechange=function(){
  32.     loadpage(page_request, containerid)
  33.   }
  34.  
  35.   page_request.open('GET', url, true)
  36.   page_request.send(null)
  37. }
  38.  
  39. function loadpage(page_request, containerid){
  40.   if (page_request.readyState == 4 
  41.   && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  42.     document.getElementById(containerid).innerHTML=page_request.responseText
  43. }
  44.  
  45. function loadobjs(){
  46.   if (!document.getElementById)
  47.     return
  48.  
  49.   for (i=0; i<arguments.length; i++){
  50.     var file=arguments[i]
  51.     var fileref=""
  52.  
  53.     if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
  54.       if (file.indexOf(".js")!=-1){ //If object is a js file
  55.         fileref=document.createElement('script')
  56.         fileref.setAttribute("type","text/javascript");
  57.         fileref.setAttribute("src", file);
  58.       }
  59.       else if (file.indexOf(".css")!=-1){ //If object is a css file
  60.         fileref=document.createElement("link")
  61.         fileref.setAttribute("rel", "stylesheet");
  62.         fileref.setAttribute("type", "text/css");
  63.         fileref.setAttribute("href", file);
  64.       }
  65.     }
  66.  
  67.     if (fileref!=""){
  68.       document.getElementsByTagName("head").item(0).appendChild(fileref)
  69.       loadedobjects+=file+" " //Remember this object as being already added to page
  70.     }
  71.   }
  72. }
  73.  
  74. </script>
  75.  
As you can probably telll from the header I got this code from http://www.dynamicdrive.com/dynamici...jaxcontent.htm


An alternitive method to use if the is only a small amount of data involved is to use PHP to write some Javascript that defines variables containing all the data (a 2 dimensional array of cities and names would do it). However I would only recomend doing this for a reasonable small amount of data.
Newbie
 
Join Date: Jul 2006
Posts: 4
#3: Aug 28 '06

re: PHP - Dynamic Drop Down Menu


I have to create a 4drop down menus in starting only first drop down menu is having list rest three are blank then after i select first drop down value then next drop down menu have there corresponding values then third drop down will have there values then fourth ..
How will i do this i need in PHP or Javascript.
aman
Newbie
 
Join Date: Jul 2006
Posts: 4
#4: Aug 28 '06

re: PHP - Dynamic Drop Down Menu


Dynamic Drop Down Menu
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,202
#5: Aug 28 '06

re: PHP - Dynamic Drop Down Menu


Well you only need PHP if the data is being sourced from a database or some other server based location (a file).

When I list selection is made you will either need to reload the page with the new information or have already got all the information in the page and only display the relevent options. This will require javascript.
Newbie
 
Join Date: Jul 2007
Posts: 2
#6: Jul 30 '07

re: PHP - Dynamic Drop Down Menu


Quote:

Originally Posted by mart2006

Hi,

I'm fairly new to PHP and I've created a dynamic drop down menu that populates itself with data from a MySQL table. What I would like to do is create a non dynamic drop down menu that alters what is shown in the dynamic menu.

For example, the first menu has three cities London, Paris, New York. If I choose London it populates the second menu with people from London.

Here is the code I have for my dynamic menu

Expand|Select|Wrap|Line Numbers
  1. <td valign=top><strong>Name:</strong></td>
  2.     <td>
  3.     <?php
  4.     echo "<select name=\"name\">"; 
  5.     echo "<option size =30 selected>Select</option>";
  6.     if(mysql_num_rows($sql_result)) 
  7.     { 
  8.     while($row = mysql_fetch_assoc($sql_result)) 
  9.     { 
  10.     echo "<option>$row[name]</option>"; 
  11.     } 
  12.  
  13.     } 
  14.     else {
  15.     echo "<option>No Names Present</option>";  
  16.     } 
  17.     ?>
  18.     </td>
  19.     </tr>    
  20.  
So basically, I need a standard menu, i.e:

Expand|Select|Wrap|Line Numbers
  1. <tr>
  2.     <td valign=top><strong>Sites:</strong></td>
  3.     <td> <select name="cities">
  4.     <option selected>Select</option>
  5.     <option>London</option>
  6.     <option>Paris</option>
  7.     <option>New York</option>
  8.     </select>
  9.     </tr>
  10.     </td>
  11.  
I think I need to hold the value of cities when selected in a variable and create an if statement with various sql query results to be run depending on what option is chosen.

Any help would be highly appreciated!

Thanks,
Mart



Hey Mart,

I've recently done the same thing. What ever you name your select box will the name of the POSTED value of the drop down. i.e.
<select name="city">
<option>London</option>
<option>Paris</option>
<option>New York</option>
</select>

You would have a table for each city which would contain a list of users you would then submit that to some PHP code that would include something to the effect of ...

<?php $city=$_POST['city'];
//construct lookup statementins

$sql="select people from $city where city= '$city'";

$result=mysql_query($sql,$conn) or die (mysql_error());

if(mysql_num_rows($result)) {
while($row = mysql_fetch_row($result))
{

print("<option value=\"$row[0]\">$row[0]</option>");
}
}
else {
print("<option value=\"\">No courses created yet</option>");
}

?>

That'll work of coruse you don't mind reloading the page. This also will not take care of duplicate names that you may have in the DB.
nathj's Avatar
Expert
 
Join Date: May 2007
Location: North Tyneside
Posts: 857
#7: Jul 30 '07

re: PHP - Dynamic Drop Down Menu


Hi,

It is possible to achieve exactly what uuo are after using a combination of HTML, PHP, MySQL and JavaScript.

First the data structure - as this will be vital.

From what I ahev read on this thread for this idea you need three tables:
1) The Cities
2) The people
3) The link/association between the two

This is a standarad structure for potential many-to many data relationships. It works perfectly and is properly normalised.

Second the HTML - this is just a form, the combo box of cities, which can be populated from the database, should have an onchange that calls a javascript.

Third the JavaScript - this uses XMLHTTPREQUEST to get the data from the database via the Fourth and final item - the PHP.

This structure works a treat, I'm using on a site that is testing at the moment.

Have a read of the PHP AJAX tutorial from W3Schools and have a go.

If you get stuck post the problem back here.

I hope this points you in the right direction. But it is definitley possible to have the page refresh as you are on it.

Cheers
nathj
Newbie
 
Join Date: Aug 2007
Posts: 26
#8: Aug 2 '07

re: PHP - Dynamic Drop Down Menu


Quote:

Originally Posted by nathj

Hi,

It is possible to achieve exactly what uuo are after using a combination of HTML, PHP, MySQL and JavaScript.

First the data structure - as this will be vital.

From what I ahev read on this thread for this idea you need three tables:
1) The Cities
2) The people
3) The link/association between the two

This is a standarad structure for potential many-to many data relationships. It works perfectly and is properly normalised.

Second the HTML - this is just a form, the combo box of cities, which can be populated from the database, should have an onchange that calls a javascript.

Third the JavaScript - this uses XMLHTTPREQUEST to get the data from the database via the Fourth and final item - the PHP.

This structure works a treat, I'm using on a site that is testing at the moment.

Have a read of the PHP AJAX tutorial from W3Schools and have a go.

If you get stuck post the problem back here.

I hope this points you in the right direction. But it is definitley possible to have the page refresh as you are on it.

Cheers
nathj

Thanks for this - I have had a similar problem in populating a second select menu from the first, where both lists are generated from mySQL. Your suggestion works in FF, Safari and Opera very well, but in IE the select menu which is meant to be repopulated remains blank.

I have tested the database, php page and js file, and all of these seem to work. The problem is in populating the <select> tag using the .innerHTML command (it repopulates a div tag without any problem). My code is as follows:

HTML file:
Expand|Select|Wrap|Line Numbers
  1. <select name="supervisor" id="supervisor">
  2.             <option value="none">please select...</option>
  3.           </select> 
  4.  
js command:
Expand|Select|Wrap|Line Numbers
  1. function stateChanged() 
  2. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  3.  { 
  4.  document.getElementById("supervisor").innerHTML=xmlHttp.responseText 
  5.  } 
  6. }
  7.  
php:
Expand|Select|Wrap|Line Numbers
  1. do { 
  2.  
  3.        echo  "<option value=\"";
  4.         echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
  5.         echo "\">"; echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
  6.         echo "</option>\n"; 
  7.  
  8.           }  while ($row_rs_subsup = mysql_fetch_assoc($rs_subsup));
  9.  
I have tried a number of ways to get around this (e.g. playing with the js command), but I haven't really got anywhere - any suggestions would be greatly appreciated.
nathj's Avatar
Expert
 
Join Date: May 2007
Location: North Tyneside
Posts: 857
#9: Aug 3 '07

re: PHP - Dynamic Drop Down Menu


If IE will re-populate a div tag no problem then how about doing that. So when the seonc dropdown is populated you actually re-create it?

It's a bit crazy I know but it should still work on the other browsers as well.

Cheers
nathj
Newbie
 
Join Date: Aug 2007
Posts: 26
#10: Aug 3 '07

re: PHP - Dynamic Drop Down Menu


Yes, it's now working, finally ending a long struggle - thanks a lot!!



The whole select menu is wrapped in a div tag, and with the php code amended as follows:

Expand|Select|Wrap|Line Numbers
  1. echo "<select name=\"supervisor\" id=\"supervisor\">\n";
  2. echo "<option value=\"none\">please select...</option>\n";
  3.  
  4. do { 
  5.  
  6.  
  7.       echo  "<option value=\"";
  8.         echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
  9.         echo "\">"; echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
  10.         echo "</option>\n"; 
  11.  
  12.           }  while ($row_rs_subsup = mysql_fetch_assoc($rs_subsup));
  13.  
  14.  echo "</select>"; 
nathj's Avatar
Expert
 
Join Date: May 2007
Location: North Tyneside
Posts: 857
#11: Aug 3 '07

re: PHP - Dynamic Drop Down Menu


Quote:

Originally Posted by erp23

Yes, it's now working, finally ending a long struggle - thanks a lot!!



The whole select menu is wrapped in a div tag, and with the php code amended as follows:

Expand|Select|Wrap|Line Numbers
  1. echo "<select name=\"supervisor\" id=\"supervisor\">\n";
  2. echo "<option value=\"none\">please select...</option>\n";
  3.  
  4. do { 
  5.  
  6.  
  7.      echo "<option value=\"";
  8.      echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
  9.         echo "\">"; echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
  10.         echo "</option>\n"; 
  11.  
  12.          } while ($row_rs_subsup = mysql_fetch_assoc($rs_subsup));
  13.  
  14. echo "</select>"; 

I'm glad it's got sorted.

All the best with the rest of the project.

Cheers
nathj
Newbie
 
Join Date: Nov 2007
Posts: 1
#12: Nov 5 '07

re: PHP - Dynamic Drop Down Menu


Hi erp23,
could you send me the entire code for these menus? I'm new to PHP and need to create a 3 -field menu derived from 3 DB dependent tables
Thanks in advance
Newbie
 
Join Date: Nov 2007
Posts: 1
#13: Nov 12 '07

re: PHP - Dynamic Drop Down Menu


Hi:

could you email me the code for these menus to, I need the same thing and I've been racking my brain over it for days now...

Richard

<email Removed-Moderator>
Newbie
 
Join Date: Nov 2007
Posts: 1
#14: Nov 23 '07

re: PHP - Dynamic Drop Down Menu


would the following code work if say i had one simple database 'mp3 players'

and the 1st select box has been hard coded to have 3 manufacturers held within it, after selecting the 1st select the next one is generated from that just getting the name of the items i.e. 1select APPLE 2nd select gets things such as ipod nano, ipod touch etc, the examples above all seem to use multiple databases.

basically just wondering if it could be implemented on a single database??

thanks

dan
Newbie
 
Join Date: Nov 2007
Posts: 1
#15: Nov 26 '07

re: PHP - Dynamic Drop Down Menu


I also need the same code thing.
I'm totally new to PHP. I'm trying to create a new field in member profile for a IBP forum without using Custom Profile Field.
Newbie
 
Join Date: Dec 2007
Posts: 7
#16: Dec 3 '07

re: PHP - Dynamic Drop Down Menu


would anyone send me an example code for drop down menus???at least 3 drop down???just an example???thanks
Newbie
 
Join Date: Dec 2007
Posts: 7
#17: Dec 3 '07

re: PHP - Dynamic Drop Down Menu


could you send me the entire code for these menus? I'm new to PHP and need to create a 3 -field menu derived from 3 DB dependent tables
Thanks
Newbie
 
Join Date: Apr 2006
Posts: 3
#18: Oct 17 '08

re: PHP - Dynamic Drop Down Menu


I am pasting some code here in case you wanted to see how you can use database items to create a Drop Down Menu instead of a Drop Down List. The menu uses CSS to show/hide elements.

Please note the database used in the example is not MySQL but txt-db-api, which is a text-file database available for php.




Expand|Select|Wrap|Line Numbers
  1. <?//horizontal menu bar *****************************************************************
  2. $rs1=$db->executeQuery("SELECT * FROM sch_pages WHERE p_parpage=0 ORDER BY p_order");
  3. while($rs1->next())
  4. {
  5. list($p_id, $p_name, $p_sysname, $p_order, $p_prot, $p_pass, $p_nomenu, $p_coded, $p_https, $p_parpage)=$rs1->getCurrentValues();
  6. if($p_nomenu==0)
  7. {
  8. ?>
  9.  
  10.  
  11. <ul id="nav">
  12.     <li><a HREF="index.php?sch_action=display_content&c_page=<?echo $p_id?>"><? echo $p_name ?></a>
  13.         <ul>    
  14.  
  15.  
  16.       <?//drop down submenu bar ***************************************************************
  17.       $rs2=$db->executeQuery("SELECT * FROM sch_pages WHERE p_parpage=$p_id ORDER BY p_order");
  18.       while($rs2->next())
  19.       {
  20.       list($p_id, $p_name, $p_sysname, $p_order, $p_prot, $p_pass, $p_nomenu, $p_coded, $p_https, $p_parpage)=$rs2->getCurrentValues();
  21.       if($p_nomenu==0){?>                
  22.               <li><a HREF="index.php?sch_action=display_content&c_page=<?echo $p_id?>"><? echo $p_name ?></a></li>                
  23.             <?}
  24.       }
  25.       ?>
  26.  
  27.  
  28.         </ul>
  29.     </li>    
  30. </ul>
  31.  
  32.  
  33. <?
  34. }
  35. }
  36. ?>    
  37.  
  38.  
  39.  
  40.  
Expand|Select|Wrap|Line Numbers
  1. <script>
  2. sfHover = function() {
  3.     var sfEls = document.getElementById("nav").getElementsByTagName("LI");
  4.     for (var i=0; i<sfEls.length; i++) {
  5.         sfEls[i].onmouseover=function() {
  6.             this.className+=" sfhover";
  7.         }
  8.         sfEls[i].onmouseout=function() {
  9.             this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
  10.         }
  11.     }
  12. }
  13. if (window.attachEvent) window.attachEvent("onload", sfHover);
  14. </script>
  15.  
Expand|Select|Wrap|Line Numbers
  1. <style>
  2. #nav, #nav ul {
  3.     padding: 0;
  4.     margin: 0;
  5.     list-style: none;
  6. }
  7. #nav a {
  8.     display: block;
  9.     width: 10em;
  10. }
  11. #nav li {
  12.     float: left;
  13.     width: 10em;
  14. }
  15. #nav li ul {
  16.     position: absolute;
  17.     width: 10em;
  18.     left: -999em;
  19. }
  20. #nav li:hover ul {
  21.     left: auto;
  22. }
  23. #nav li:hover ul, #nav li.sfhover ul {
  24.     left: auto;
  25. }
  26. </style>
Newbie
 
Join Date: Oct 2008
Posts: 16
#19: Oct 21 '08

re: PHP - Dynamic Drop Down Menu


Hi moderator,

Sorry for OOT,
Is it allowed here to post some advertisements in the middle of discussion like above?

Thanks

<Answer: No it is not. It's been removed. --Atli>
Newbie
 
Join Date: Feb 2009
Posts: 1
#20: Feb 25 '09

re: PHP - Dynamic Drop Down Menu


Quote:

Originally Posted by didgy58 View Post

would the following code work if say i had one simple database 'mp3 players'

and the 1st select box has been hard coded to have 3 manufacturers held within it, after selecting the 1st select the next one is generated from that just getting the name of the items i.e. 1select APPLE 2nd select gets things such as ipod nano, ipod touch etc, the examples above all seem to use multiple databases.

basically just wondering if it could be implemented on a single database??

thanks

dan

While the previous posts aren't necessary referring to multiple databases, but more than likely multiple tables within a database. Neither is necessary based on your example. You can have one table in a database that has X number of fields. 3 fields in your example..1 for a unique identifier of the record (gid), 1 for the manufacturer (maker), and one for the model (model).

Then to avoid calling to the database all the time, I would essentially pull the entire database at one go, and populate it out to PHP arrays multi-dimensional arrays.

Of course depending on volume of data in the table, it may be smarter to do multiple queries to the database depending on selection. Given the relatively small number of players available on the market though, I wouldn't sacrifice the overhead of making the multiple calls.

Note** There are also many ways to work with internal arrays within PHP with the data, up to you to figure out which one is going to work best for your sitaution, whether you need one large mult-dimensional array, or a grouping of multiple types of arrays.
Newbie
 
Join Date: Nov 2009
Posts: 1
#21: 6 Days Ago

re: PHP - Dynamic Drop Down Menu


can u please sned me the full codes
Thanks in advance
Reply