473,287 Members | 1,651 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

PHP - Dynamic Drop Down Menu

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.
Mar 6 '06 #1
19 258936
Banfa
9,065 Expert Mod 8TB
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.
Mar 7 '06 #2
aman
4
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
Aug 28 '06 #3
aman
4
Dynamic Drop Down Menu
Aug 28 '06 #4
Banfa
9,065 Expert Mod 8TB
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.
Aug 28 '06 #5
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.
Jul 30 '07 #6
nathj
938 Expert 512MB
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
Jul 30 '07 #7
erp23
26
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.
Aug 2 '07 #8
nathj
938 Expert 512MB
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
Aug 3 '07 #9
erp23
26
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>"; 
Aug 3 '07 #10
nathj
938 Expert 512MB
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
Aug 3 '07 #11
eugrin
1
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
Nov 5 '07 #12
meriad
1
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>
Nov 12 '07 #13
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
Nov 23 '07 #14
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.
Nov 26 '07 #15
would anyone send me an example code for drop down menus???at least 3 drop down???just an example???thanks
Dec 3 '07 #16
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
Dec 3 '07 #17
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>
Oct 17 '08 #18
agun
16
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>
Oct 21 '08 #19
@didgy58
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.
Feb 25 '09 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: jorntk | last post by:
How can i make a drop down menu that are dynamiclly generated base on the value selected in another drop down menu? thanks nad regards Jorn
6
by: Greg Scharlemann | last post by:
I am attempting to populate a drop down menu based on the selection of a different drop down menu. However, it is not working correctly, I cannot figure out for the life of me what exactly happens...
1
by: tribal boy | last post by:
Guys, I am using a dynamic menu which uses xml,xsl a css file and javascript. This works fine when there are no server controls around or underneath it. The problem is whenever the menu...
3
by: scaredemz | last post by:
hi, so i'm creating a dynamic drop-down menu. the menu and the text show up fine in IE but only the drop-down shows in Firefox without the menu text. Below is the fxn code. help pls. function...
6
by: mcgrew.michael | last post by:
I hope this is the right group. I am very new to ASP so this is probably a stupid question. I have some vbscript that query's AD and populates a recordset. I know the recorset contains the...
4
by: TycoonUK | last post by:
Hi, As I do not have IE7 on my computer, I was wondering if there is a fault in my CSS Menu when using IE7. Please can someone look at my site - http://www.worldofmonopoly.co.uk and tell me...
1
by: azeemqaiser | last post by:
Hi All, I have a form with two drop down controls. I want to change the values of Drop Down Menu 2 if i select some value in Drop Down Menu 1. Like If i select country then all the states of...
2
by: vinceboy | last post by:
Hi anybody. I am newbie here and would like to know that how can I validate both drop down menu and radio button from a dynamic display form.Something went wrong with my script.The radio button is...
10
by: mart2006 | last post by:
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.