PHP - Dynamic Drop Down Menu

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mart2006
    New Member
    • Mar 2006
    • 12

    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

    Code:
    <td valign=top><strong>Name:</strong></td>
    	<td>
    	<?php
    	echo "<select name=\"name\">"; 
    	echo "<option size =30 selected>Select</option>";
    	if(mysql_num_rows($sql_result)) 
    	{ 
    	while($row = mysql_fetch_assoc($sql_result)) 
    	{ 
    	echo "<option>$row[name]</option>"; 
    	} 
    
    	} 
    	else {
    	echo "<option>No Names Present</option>";  
    	} 
    	?>
    	</td>
    	</tr>
    So basically, I need a standard menu, i.e:

    Code:
    <tr>
    	<td valign=top><strong>Sites:</strong></td>
    	<td> <select name="cities">
    	<option selected>Select</option>
    	<option>London</option>
    	<option>Paris</option>
    	<option>New York</option>
    	</select>
    	</tr>
    	</td>
    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.
    Last edited by mart2006; Mar 6 '06, 10:04 PM.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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

    Code:
    <script type="text/javascript">
    
    /***********************************************
    * Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
    * This notice MUST stay intact for legal use
    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
    ***********************************************/
    
    var loadedobjects=""
    var rootdomain="http://"+window.location.hostname
    
    function ajaxpage(url, containerid){
      var page_request = false
    
      if (window.XMLHttpRequest) // if Mozilla, Safari etc
        page_request = new XMLHttpRequest()
      else if (window.ActiveXObject){ // if IE
        try {
          page_request = new ActiveXObject("Msxml2.XMLHTTP")
        } 
        catch (e){
          try{
            page_request = new ActiveXObject("Microsoft.XMLHTTP")
          }
          catch (e){}
        }
      }
      else
        return false
    
      page_request.onreadystatechange=function(){
        loadpage(page_request, containerid)
      }
    
      page_request.open('GET', url, true)
      page_request.send(null)
    }
    
    function loadpage(page_request, containerid){
      if (page_request.readyState == 4 
      && (page_request.status==200 || window.location.href.indexOf("http")==-1))
        document.getElementById(containerid).innerHTML=page_request.responseText
    }
    
    function loadobjs(){
      if (!document.getElementById)
        return
    
      for (i=0; i<arguments.length; i++){
        var file=arguments[i]
        var fileref=""
    
        if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
          if (file.indexOf(".js")!=-1){ //If object is a js file
            fileref=document.createElement('script')
            fileref.setAttribute("type","text/javascript");
            fileref.setAttribute("src", file);
          }
          else if (file.indexOf(".css")!=-1){ //If object is a css file
            fileref=document.createElement("link")
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", file);
          }
        }
    
        if (fileref!=""){
          document.getElementsByTagName("head").item(0).appendChild(fileref)
          loadedobjects+=file+" " //Remember this object as being already added to page
        }
      }
    }
    
    </script>
    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.

    Comment

    • aman
      New Member
      • Jul 2006
      • 4

      #3
      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

      Comment

      • aman
        New Member
        • Jul 2006
        • 4

        #4
        Dynamic Drop Down Menu

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          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.

          Comment

          • RamseySkywalker
            New Member
            • Jul 2007
            • 2

            #6
            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

            Code:
            <td valign=top><strong>Name:</strong></td>
            	<td>
            	<?php
            	echo "<select name=\"name\">"; 
            	echo "<option size =30 selected>Select</option>";
            	if(mysql_num_rows($sql_result)) 
            	{ 
            	while($row = mysql_fetch_assoc($sql_result)) 
            	{ 
            	echo "<option>$row[name]</option>"; 
            	} 
            
            	} 
            	else {
            	echo "<option>No Names Present</option>";  
            	} 
            	?>
            	</td>
            	</tr>
            So basically, I need a standard menu, i.e:

            Code:
            <tr>
            	<td valign=top><strong>Sites:</strong></td>
            	<td> <select name="cities">
            	<option selected>Select</option>
            	<option>London</option>
            	<option>Paris</option>
            	<option>New York</option>
            	</select>
            	</tr>
            	</td>
            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>Londo n</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_q uery($sql,$conn ) or die (mysql_error()) ;

            if(mysql_num_ro ws($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.

            Comment

            • nathj
              Recognized Expert Contributor
              • May 2007
              • 937

              #7
              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

              Comment

              • erp23
                New Member
                • Aug 2007
                • 26

                #8
                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:
                Code:
                <select name="supervisor" id="supervisor">
                            <option value="none">please select...</option>
                          </select>
                js command:
                Code:
                function stateChanged() 
                { 
                if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
                 { 
                 document.getElementById("supervisor").innerHTML=xmlHttp.responseText 
                 } 
                }
                php:
                Code:
                do { 
                
                       echo  "<option value=\"";
                	    echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
                		echo "\">"; echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
                		echo "</option>\n"; 
                		  
                		  }  while ($row_rs_subsup = mysql_fetch_assoc($rs_subsup));
                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.

                Comment

                • nathj
                  Recognized Expert Contributor
                  • May 2007
                  • 937

                  #9
                  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

                  Comment

                  • erp23
                    New Member
                    • Aug 2007
                    • 26

                    #10
                    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:

                    Code:
                    echo "<select name=\"supervisor\" id=\"supervisor\">\n";
                    echo "<option value=\"none\">please select...</option>\n";
                    
                    do { 
                    
                           
                    	  echo  "<option value=\"";
                    	    echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
                    		echo "\">"; echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
                    		echo "</option>\n"; 
                    		  
                    		  }  while ($row_rs_subsup = mysql_fetch_assoc($rs_subsup));
                    		  
                     echo "</select>";

                    Comment

                    • nathj
                      Recognized Expert Contributor
                      • May 2007
                      • 937

                      #11
                      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:

                      Code:
                      echo "<select name=\"supervisor\" id=\"supervisor\">\n";
                      echo "<option value=\"none\">please select...</option>\n";
                       
                      do { 
                       
                       
                      	 echo "<option value=\"";
                      	 echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
                      		echo "\">"; echo $row_rs_subsup['firstName']; echo " "; echo $row_rs_subsup['lastName']; 
                      		echo "</option>\n"; 
                       
                      		 } while ($row_rs_subsup = mysql_fetch_assoc($rs_subsup));
                       
                      echo "</select>";
                      I'm glad it's got sorted.

                      All the best with the rest of the project.

                      Cheers
                      nathj

                      Comment

                      • eugrin
                        New Member
                        • Nov 2007
                        • 1

                        #12
                        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

                        Comment

                        • meriad
                          New Member
                          • Nov 2007
                          • 1

                          #13
                          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>
                          Last edited by ak1dnar; Nov 26 '07, 02:22 AM. Reason: email removed

                          Comment

                          • didgy58
                            New Member
                            • Nov 2007
                            • 1

                            #14
                            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

                            Comment

                            • bakakid
                              New Member
                              • Nov 2007
                              • 1

                              #15
                              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.

                              Comment

                              Working...